understanding InvalidAsynchronousStateException occurrences

后端 未结 3 1599
广开言路
广开言路 2020-12-30 00:32

When does InvalidAsynchronousStateException get thrown?

I have the following piece of code:

control.InvokeRequired ? control.Invoke(expressi

3条回答
  •  旧巷少年郎
    2020-12-30 00:48

    I've been faced to the same issue recently. My form contains several invisible user controls that may be required to appear later in the life cycle of the application. Sometimes, those requests come from background threads.

    The problem was that even if I enclose control.Visible = true inside a control.Invoke, the control was actually assigned to the background thread (as mentioned in Chris's point #3) instead of the form's main UI thread. A simple workaround for me was to call once the IWin32Window.Handle property during the creation of the parent form (for instance from the form's Load event) This ensures that the control is created in main UI thread without making it visible.

    public partial class MyForm : Form
    {
      private void MyForm_Load(object sender, EventArgs e)
      {
         ForceControlCreation(control1);
         ForceControlCreation(control2);
      }
    
      private void ForceControlCreation(IWin32Window control)
      {
        // Ensures that the subject control is created in the same thread as the parent 
        // form's without making it actually visible if not required. This will prevent 
        // any possible InvalidAsynchronousStateException, if the control is later 
        // invoked first from a background thread.
        var handle = control.Handle; 
      }
    }
    

提交回复
热议问题