如何在事件中启动任务并退出方法 [英] How to Initiate task and exit the method in an event
问题描述
嗨朋友们,
我订阅了一个活动
Hi friends,
I am subscribed to an event
public void Call_Comes(object sender, EventArgs e)
{
//Code here
}
我不想在这个活动中执行任务,因为这需要很长时间......
我想要的是收集信息和启动任务,退出活动...
我怎样才能实现这一目标?我在事件中使用了线程..但似乎事件正在等待线程完成....
任何人都可以帮助我吗??
I don't want to do the tasks to be carried out inside this event, as it will take long time...
What I want is to collect the information and initiate the task, and exit the event...
How can I achieve this ?? I have used threading inside event.. But it seems that event is waiting for the thread to finish....
Can anybody help me ??
推荐答案
有很多方法可以将事件处理程序解耦到另一个线程上;
其中一个可能对你有用;
There are many ways to decouple the event handler onto a different thread;
One of these might work for you;
// Option 1
public void Call_Comes(object sender, EventArgs e) {
Task.Factory.StartNew(() => HandleEvent(sender, e));
}
// Option 2
public void Call_Comes(object sender, EventArgs e) {
ThreadPool.QueueUserWorkItem(x => HandleEvent(sender, e));
}
// Option 3
public void Call_Comes(object sender, EventArgs e) {
var worker = new BackgroundWorker();
worker.DoWork += HandleEvent;
worker.RunWorkerAsync();
}
// Option 4
public void Call_Comes(object sender, EventArgs e)
{
var thread = new Thread(() => HandleEvent(sender, e));
thread.Start();
}
private void HandleEvent(object sender, EventArgs e) {
// Your stuff
}
请注意,如果您在其他线程上运行它,您仍需要处理任何异常。你不会在非主线程上没有被禁止的例外。
希望这会有所帮助,
Fredrik
Note that if you do run it on a different thread you still need to handle any exceptions. You don't wan't uncaught exceptions on non-main threads.
Hope this helps,
Fredrik
这篇关于如何在事件中启动任务并退出方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!