Cross thread exception

前端 未结 4 977
慢半拍i
慢半拍i 2021-01-26 05:19

I am having a problem for a while

this line:

txtPastes.Text = (string)e.UserState;

throws a cross thread exception and I didn\'t find a

相关标签:
4条回答
  • 2021-01-26 05:27

    Well, this is supposed to work of course. The cause of this exception is not visible in your snippet. What matters is exactly where and when the BackgroundWorker is started. Its RunWorkerAsync() method uses the SynchronizationContext.Current property to figure out what thread needs to execute the ProgressChanged event handler.

    This can go wrong when:

    • You started the BGW too early, before the Application.Run() call. Winforms or WPF won't yet have had a chance to install its own synchronization provider.
    • You called the BGW's RunWorkerAsync() method in a worker thread. Only marshaling to the UI thread is supported, the message loop is the crucial ingredient to make running code on another thread work.
    • The form that has txtPastes control was created on another thread. With the BGW started on the UI thread that's still a thread mismatch
    • The form's Show() method was called on another thread. Which creates the native Windows window on the wrong thread.
    0 讨论(0)
  • 2021-01-26 05:32

    You cannot update a UI control from any thread other than the UI thread. Typically, the BackgroundWorker would take care of raising its ProgressChanged and RunWorkerCompleted events correctly on the UI thread. Since that doesn’t appear to be the case here, you could marshal your UI-updating logic to the UI thread yourself by using the Invoke method:

    txtPastes.Invoke(new Action(() => 
    { 
        // This code is executed on the UI thread.
        txtPastes.Text = (string)e.UserState; 
    }));
    

    If you’re on WPF, you would need to call Invoke on the control’s dispatcher:

    txtPastes.Dispatcher.Invoke(new Action(() => 
    { 
        txtPastes.Text = (string)e.UserState; 
    }));
    

    Update: As Thomas Levesque and Hans Passant have mentioned, you should investigate the reason why your ProgressChanged event is not being raised on the UI thread. My suspicion is that you’re starting the BackgroundWorker too early in the application initialization lifecycle, which could lead to race conditions and possibly a NullReferenceException if the first ProgressChanged event is raised before your txtPastes textbox has been initialized.

    0 讨论(0)
  • 2021-01-26 05:38

    If you want to update yout GUI for example TextBox, you should read this article:

    Update GUI from another thread

    0 讨论(0)
  • 2021-01-26 05:39

    Make sure you start the BackgroundWorker from the UI thread; if you do that, the ProgressChanged event will be raised on that thread, and the exception won't happen.

    0 讨论(0)
提交回复
热议问题