RSS

Tag Archives: exception

C# Cross Thread Exception on Subform

I was having an issue where I had a textbox control on a sub form and calling subform.show() after an update would cause a cross thread exception (even using invoke). The problem was I created a subform (with the textbox control) and added text to the textbox before the sub form was displayed. The problem is that the handle for the control was not created yet and invokerequired was false because of this. Thus the thread that updated my control actually caused the control’s handle to be created. When I called the subform.show(), it would try to access the control on the GUI thread and not the thread that had created it. See below:

Example:

Subform _Sub
 
Public MainForm()
{
    _Sub = new Subform();
    // Sub form’s handle is not created yet.
}
 
 
// If this method is called  on a different thread before the sub form (show) is
// called on the GUI thread, a cross thread exception can occur.
// -This method will append to a text box on the sub form.
private void appendToSubForm(string text)
{
        //  Invoke will not be required since the handle has not yet been created.
        if (_Sub.InvokeRequired)
        {
            _ Sub.Invoke((Action)appendToDebugLog, text);
        }
        else
        {
            if (_Sub == null || _ Sub.IsDisposed)
            {
                return;
            }
            // This method which will append to textbox will cause the sub form’s handle to be created
            // on the thread this method is called on.
            _Sub.AppendToMe(text);
        }
}
 
// SOLUTION:
// Call this.CreateHandle() on the Sub form in order to force creation of the handle when the constructor is called.
 
// Required to create the handle on the thread that the constructor is called on.
// In our case, the GUI thread.  This prevents cross threading if the handle
// is created on a non GUI thread.
this.CreateHandle();

Advertisements
 
1 Comment

Posted by on August 22, 2011 in .net, c#

 

Tags: , , , , , , ,