开发者

How to use Tasks to simplify Delegate.BeginInvoke/Delegate.EndInvoke?

开发者 https://www.devze.com 2023-04-08 23:05 出处:网络
Trying to wrap my head around the Tasks class, and more sp开发者_C百科ecifically, the Task.Factory.FromAsync method.

Trying to wrap my head around the Tasks class, and more sp开发者_C百科ecifically, the Task.Factory.FromAsync method.

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. 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. 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.

You can start a Task with the Task.Factory.StartNew Method*:

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消