【发布时间】:2011-11-17 20:05:23
【问题描述】:
我有一个 WPF 窗口,我想在后台线程中做一些工作..
当工作完成后,我想再做一次.. 就像一个循环之间的 UI 更新
我的代码:
private void InitializeBackgroundWorker()
{
m_stopCamera = false;
m_worker = new BackgroundWorker();
m_worker.DoWork += new DoWorkEventHandler(worker_DoWork);
m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
m_worker.WorkerSupportsCancellation = true;
}
unsafe void worker_DoWork(object sender, DoWorkEventArgs e)
{
// my work....
e.Result = new MyResultClass(p1,p2..);
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
return;
if (e.Error != null)
{
Logger.LogException(e.Error.ToString());
Window_Closed(this, new EventArgs());
}
try
{
//UI work..
DetectionResult result = e.Result as DetectionResult;
if (result.Cancel == true)
{
m_DetectedObjID = result.DetectionID;
// PlaySound();
audio_MediaEnded(this, new EventArgs());
}
else
((BackgroundWorker)sender).RunWorkerAsync();
}
catch (Exception ex)
{
Logger.LogException(ex.ToString());
Window_Closed(this,new EventArgs());
}
}
我知道这段代码不好,因为我遇到了线程地狱,无法正确调试它
例如..当代码运行时,我点击关闭按钮,我可以在事件中看到 工人一直很忙..导致无限循环..
private void Window_Closed(object sender, EventArgs e)
{
if (m_worker.IsBusy)
m_worker.CancelAsync();
while(m_worker.IsBusy);
base.Close();
}
}
我做错了什么?谢谢
【问题讨论】:
-
您能否说明如何处理
worker_DoWork方法中的挂起取消? -
我不处理它..仅在 RunWorkerCompleted 事件中
-
在下面阅读我的答案。你需要自己设置
e.Cancelled为true。
标签: c# wpf winforms multithreading