简体   繁体   English

如何使用任务来简化Delegate.BeginInvoke / Delegate.EndInvoke?

[英]How to use Tasks to simplify Delegate.BeginInvoke/Delegate.EndInvoke?

Trying to wrap my head around the Tasks class, and more specifically, the Task.Factory.FromAsync method. 试图绕过Tasks类,更具体地说是Task.Factory.FromAsync方法。

Currently in my code I am doing something like this: 目前,在我的代码中,我正在执行以下操作:

var handler = MyEvent;

if (handler != null)
{
    handler.Invoke(this, e);
}

Unfortunately, this is synchronous and I am looking for the asynchronous version. 不幸的是,这是同步的,我正在寻找异步版本。 I could use BeginInvoke and EndInvoke but it seems like a bit of a waste considering I don't need a callback. 我可以使用BeginInvoke和EndInvoke,但考虑到我不需要回调,这似乎有点浪费。 I believe I heard somewhere it is possible to use one of the Task.Factory methods to simplify this call where a dummy callback would then not be necessary. 我相信我在某处听说可以使用Task.Factory方法之一来简化此调用,而此时无需使用伪回调。 Could anyone enlighten me? 谁能启发我?

It's somewhat unusual to invoke event handlers asynchronously; 异步调用事件处理程序有点不寻常。 if the handler wants to process the event asynchronously, it should start a Task itself. 如果处理程序想要异步处理事件,则应自行启动Task。

You can start a Task with the Task.Factory.StartNew Method *: 您可以使用Task.Factory.StartNew方法 *启动任务:

void MyClass_MyEvent(object sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        // do work
    });
}

(* or the Task.Run Method in the Async CTP or .NET 4.5) (*或Async CTP或.NET 4.5中的Task.Run方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM