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)
精彩评论