Cross thread exception

前端 未结 4 979
慢半拍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.

提交回复
热议问题