简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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