我有一段时间遇到问题
这一行:
txtPastes.Text = (string)e.UserState;
抛出跨线程异常,我没有找到任何解决方案
txtPastes
- 文本框
GuiUpdate
- 后台工作者
lstAllPastes
- 字符串列表
private void GuiUpdate_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
while (lstAllPastes.Count == 0) ;
for (int i = 0; i < lstAllPastes[0].Length; i++)
{
GuiUpdate.ReportProgress(0, lstAllPastes[0].Substring(0, i));
Thread.Sleep(1);
}
lstAllPastes.RemoveAt(0);
}
}
private void GuiUpdate_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
txtPastes.Text = (string)e.UserState;
}
private void GuiUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
您无法从 UI 线程以外的任何线程更新 UI 控件。通常,BackgroundWorker
将负责提高其ProgressChanged
and RunWorkerCompleted
UI 线程上正确的事件。由于这里的情况似乎并非如此,因此您可以使用以下方法自行将 UI 更新逻辑编组到 UI 线程:Invoke
method:
txtPastes.Invoke(new Action(() =>
{
// This code is executed on the UI thread.
txtPastes.Text = (string)e.UserState;
}));
如果您使用 WPF,则需要致电Invoke
在控件的调度程序上:
txtPastes.Dispatcher.Invoke(new Action(() =>
{
txtPastes.Text = (string)e.UserState;
}));
Update:正如托马斯·莱维斯克(Thomas Levesque)和汉斯·帕桑特(Hans Passant)所提到的,你应该调查你的原因ProgressChanged
UI 线程上未引发事件。我怀疑你正在开始BackgroundWorker
应用程序初始化生命周期过早,这可能会导致竞争条件,并可能导致NullReferenceException
如果第一个ProgressChanged
事件在您之前引发txtPastes
文本框已初始化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)