How to handle error "Invoke or BeginInvoke cannot be called on a control until the window handle has been created"

This error often occurs when you handle a UI Control that has not been created (ie not yet on the window) but you call Invoke of BeginInvoke before

How to fix:

Way 1: Check handle has been created or not 

if(uiControl.IsHandleCreated)
{
    uiControl.Invoke((MethodInvoker)delegate
    {
        // Your code here.
    });
}
else
{
    // Handle has not yet been created.
    // You may want to handle this situation differently.
}
Way 2: Use SynchronizationContext . This is a mechanism that helps you queue code for Thread UI to process

// Get the UI synchronization context.
SynchronizationContext uiContext = SynchronizationContext.Current;
// Post a delegate to the UI thread.
uiContext.Post(new SendOrPostCallback((state) =>
{
    // Your code here.
}), null);

Post a Comment

Previous Post Next Post