当具有活动事件处理程序的线程退出时会发生什么? [英] What happens when a thread with active event handler exits ?
本文介绍了当具有活动事件处理程序的线程退出时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果它直接退出,如何让线程等待事件处理程序完成。
我尝试过:
尝试通过睡眠阻止线程的不同方法,等待退出等......但似乎没有什么是正确的方法。
if it directly exits, how to make a thread wait for event handler to finish.
What I have tried:
tried diferent ways to block thread by sleeping, wait for exit etc... but nothing seemed to be the right way.
推荐答案
您必须使用事件等待句柄对象。你不应该做睡眠
,任何旋转等待,没有这样的。如果你等待某个对象,你的线程将进入等待状态:它被关闭并且没有被调度回执行,直到它被唤醒,在等待状态下花费零CPU时间。你也可以等一个帖子。
请看我过去的答案:
暂停正在运行的线程 [ ^ ],
在webservice中运行一个永远不会终止的作业/线程/进程(asp.net) [ ^ ],>
使代码线程安全 [ ^ ],
Thread中的ManualResetEvent和AutoResetEvent [ ^ ]。
等待一些线程完成,也处于等待状态,你可以使用System.Threading.Thread.Join
:
Tread.Join Method(System.Threading) [ ^ ] 。
-SA
You have to use an event wait handle object. No way you should doSleep
, any spin wait, nothing like that. If you wait for some object, your thread goes to a wait state: it is switched off and not scheduled back to execution until it is waken up, spending zero CPU time in wait state. You can also wait for a thread.
Please see my past answers:
pause running thread[^],
Running exactly one job/thread/process in webservice that will never get terminated (asp.net)[^],
Making Code Thread Safe[^],
ManualResetEvent and AutoResetEvent in Thread[^].
To wait for some thread to finish, also in a wait state, you can useSystem.Threading.Thread.Join
:
Thread.Join Method (System.Threading)[^].
—SA
我觉得使用相对较新的
async
C#的功能是实现异步方法的最佳方法,因为它在完成时为方法提供了一个退出点。您可以像这样使用它
I feel that using the relatively new
async
feature of C# is the best way to implement asynchronous methods because it provides an exit point for the method when it completes. You can use it like this
//subscribe to the event
button.Click += MyEventHandlerAsync;
// When the event fires this handler is called
private async void MyEventHandlerAsync(object sender, RoutedEventArgs e)
{
//the UI thread starts the task here and then returns
//the task runs on the threadpool
string text = await Task.Run(() => this.MyMethodThatReturnsAString());
//When the task finishes, control returns here
//Do something with the result
//Set a label on the UI thread
this.label.Content = text;
}
private string MyMethodThatReturnsAString()
{
//Long running method that finds the meaning of life
//........
return "Forty Two ";
}
这篇关于当具有活动事件处理程序的线程退出时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文