Cross thread exception

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

提交回复
热议问题