unk*_*bie 7 .net c# events multithreading
这是我班上的一个片段:
public bool start()
{
Thread startThread = new Thread(this.ThreadDealer);
startThread.Start();
return _start;
}
Run Code Online (Sandbox Code Playgroud)
在ThreadDealer()中,我将布尔变量"_start"设置为false或true.我现在需要但似乎无法弄清楚是一个事件来提醒start()在ThreadDealer() - Thread完成时执行它的return语句.
我尝试使用AutoResetEvent和.WaitOne(),但是因为我有一个只阻止所有内容的GUI,而它完成了我需要它做的事情(等待线程完成),如果它阻止我的GUI就没用了.
任何帮助将非常感激.
Hei*_*nzi 25
你想做什么 - 在UI线程的方法中等待后台线程,但仍然允许UI响应 - 是不可能的.您需要将代码分成两部分:一部分在开始(或并行)后台线程之前执行,另一部分在后台线程完成后运行.
最简单的方法是使用BackgroundWorker类.它在RunWorkerCompleted工作完成后在UI thread()中引发一个事件.这是一个例子:
public void start()
{
var bw = new BackgroundWorker();
// define the event handlers
bw.DoWork += (sender, args) => {
// do your lengthy stuff here -- this will happen in a separate thread
...
};
bw.RunWorkerCompleted += (sender, args) => {
if (args.Error != null) // if an exception occurred during DoWork,
MessageBox.Show(args.Error.ToString()); // do your error handling here
// Do whatever else you want to do after the work completed.
// This happens in the main UI thread.
...
};
bw.RunWorkerAsync(); // starts the background worker
// execution continues here in parallel to the background worker
}
Run Code Online (Sandbox Code Playgroud)
刚举起一个活动.它将在错误的线程上运行,因此无论事件处理程序必须通过编组调用来处理它,如果有必要更新任何UI.通过使用Control.Begin/Invoke或Dispatcher.Begin/Invoke,取决于您使用的类库.
或者使用BackgroundWorker类,它会自动执行.
| 归档时间: |
|
| 查看次数: |
35795 次 |
| 最近记录: |