等待事件完成(线程) [英] Wait for an event to finish (threading)

查看:47
本文介绍了等待事件完成(线程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要等待一个事件结束才能继续.

I need to wait for an event to finish before continuing.

这是我的代码:

foreach (KeyValuePair<string, Stream> pair in this.XMLCollection)
{
    ...
    this.eventAggregator.GetEvent<LogToApplicationEvent>().Publish(credentials);
    //wait 
    ...
}

在继续之前,我需要等待登录"事件完全执行.我尝试使用 Task.Factory,但它对我不起作用,或者我无法正确使用它...

Before continuing I need to wait for "login" event to execute complately. I tried using Task.Factory, but it did not work for me, or I cant use it right...

此代码在演示者上,但事件更新主 UI.

This code is on presenter, but the event updates the main UI.

//publish
public virtual void Publish(TPayload payload)
{
   base.InternalPublish(payload);
}

推荐答案

至少有两种可能的解决方案:

At least two possible solutions:

后台工作者

使用 BackgroundWorker 执行您的代码,并使用 RunWorkerCompleted 事件执行完成后运行的代码.

Use a BackgroundWorker to execute your code, and use the RunWorkerCompleted event to execute the code that is run after completion.

BackgroundWorker 将基于事件的异步模式包装成一个非常易于使用的机制,完成进度报告和取消.请参阅此 BackgroundWorker 教程 和这个 SO 答案.

A BackgroundWorker wraps the event based asynchronous pattern into a very easy to use mechanism, complete with progress reporting and cancellation. See this BackgroundWorker tutorial and this SO answer .

任务(.NET 4.0 及更高版本)

使用任务 对象,并使用 ContinueWith 方法定义完成第一个任务后需要执行的代码.

Use a Task object, and use the ContinueWith method to define the code that needs to be executed after completion of the first task.

这篇关于等待事件完成(线程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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