可以使用哪些方法使线程等待事件,然后继续执行? [英] Which methods can be used to make thread wait for an event and then continue its execution?

查看:103
本文介绍了可以使用哪些方法使线程等待事件,然后继续执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程运行,委托一些任务。当一个任务完成时,会发出一个事件已经完成了。这些任务需要以特定的顺序运行,需要等待上一个任务完成。如何让线程等待,直到收到任务完成事件? (除了明显的事件处理者设置一个标志,然后一个循环轮询该标志)

解决方案

我经常使用 AutoResetEvent 等待句柄,当我需要等待异步任务完成:

  public void PerformAsyncTasks()
{
SomeClass someObj = new SomeClass()
AutoResetEvent waitHandle = new AutoResetEvent(false);
//为已完成事件创建并附加事件处理程序
EventHandler eventHandler = delegate(object sender,EventArgs e)
{
waitHandle.Set(); //表示完成的事件被提升
}
someObj.TaskCompleted + = eventHandler;

//调用异步方法
someObj.PerformFirstTaskAsync();
//等到事件处理程序被调用
waitHandle.WaitOne();
//已完成的事件已经被提出,继续下一个
someObj.PerformSecondTaskAsync();
waitHandle.WaitOne();
// ...等等
}


I have a thread running that delegates out some tasks. When a single task is complete, an event is raised saying that it has completed. These tasks need to be run in a specific order and need to wait for the previous task to finish. How can I make the thread wait until it receives the "task completed" event? (Aside from the obvious eventhandler that sets a flag and then a while loop polling the flag)

解决方案

I often use the AutoResetEvent wait handle when I need to wait for an asynchronous task to finish:

public void PerformAsyncTasks()
{
    SomeClass someObj = new SomeClass()
    AutoResetEvent waitHandle = new AutoResetEvent(false); 
    // create and attach event handler for the "Completed" event
    EventHandler eventHandler = delegate(object sender, EventArgs e) 
    {
        waitHandle.Set();  // signal that the finished event was raised
    } 
    someObj.TaskCompleted += eventHandler;

    // call the async method
    someObj.PerformFirstTaskAsync();    
    // Wait until the event handler is invoked
    waitHandle.WaitOne();
    // the completed event has been raised, go on with the next one
    someObj.PerformSecondTaskAsync();
    waitHandle.WaitOne();
    // ...and so on
}

这篇关于可以使用哪些方法使线程等待事件,然后继续执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆