C#.net - 如何警告程序线程已完成(事件驱动)?
这是我的类中的一个片段:
public bool start()
{
Thread startThread = new Thread(this.ThreadDealer);
startThread.Start();
return _start;
}
在 ThreadDealer() 中,我将布尔变量“_start”设置为 false 或 true。我现在需要但似乎无法弄清楚的是一个事件,用于在 ThreadDealer()-Thread 完成时提醒 start() 执行其返回语句。
我尝试使用 AutoResetEvent 和 .WaitOne() 进行一些操作,但由于我有一个 GUI,它只会阻止所有内容,并且当它执行我需要它执行的操作(等待线程完成)时,如果它阻止我的 GUI,则毫无用处。
任何帮助将不胜感激。
this is a snippet from my class:
public bool start()
{
Thread startThread = new Thread(this.ThreadDealer);
startThread.Start();
return _start;
}
In ThreadDealer() I'm setting the boolean variable "_start" to false or true. What I need now but can't seem to figure out is an event to alert start() to execute its return statement when the ThreadDealer()-Thread has finished.
I tried something with an AutoResetEvent and .WaitOne() but since I have a GUI that just blocks everything and while it does what I need it to do (wait for the Thread to finish) it is useless if it blocks my GUI.
Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需发起一个事件。它将在错误的线程上运行,因此任何事件处理程序都必须通过编组调用(如果需要更新任何 UI)来处理该问题。通过使用 Control.Begin/Invoke 或 Dispatcher.Begin/Invoke,具体取决于您使用的类库。
或者使用BackgroundWorker类,它会自动完成。
Just raise an event. It will run on the wrong thread so whatever event handler has to deal with that by marshaling the call if necessary to update any UI. By using Control.Begin/Invoke or Dispatcher.Begin/Invoke, depending what class library you use.
Or use the BackgroundWorker class, it does it automatically.
您想要做的事情——在 UI 线程的方法中等待后台线程,但仍然允许 UI 做出响应——是不可能的。您需要将代码分为两部分:一部分在启动(或并行)后台线程之前执行,另一部分在后台线程完成后运行。
最简单的方法是使用 BackgroundWorker 类。它在完成工作后在 UI 线程 (
RunWorkerCompleted
) 中引发一个事件。这是一个例子:What you want to do -- wait for the background thread in a method of the UI thread but still allow the UI to be responsive -- is not possible. You need to split your code into two parts: One executed before starting (or parallel to) the background thread and the other one running after the background thread has finished.
The easiest way is to use the BackgroundWorker class. It raises an event in the UI thread (
RunWorkerCompleted
) after its work is done. Here's an example: