How to return T value from BeginInvoke?

别等时光非礼了梦想. 提交于 2019-12-04 20:34:48

What you are trying to do right now is not async; if you want to return the T, just use:

return actionFunction();

It will be less overhead.

If you want async, and you are on 4.0, then the TPL may be a good option:

public Task<T> BeginInvokeExWithReturnValue<T>(Func<T> actionFunction)
{
    var task = new Task<T>(actionFunction);
    task.Start();
    return task;
}

Now the caller can use:

var task = BeginInvokeExWithReturnValue(() => Whatever());

and then when desired, check for completion, block (Wait) for completion, register continuations, etc. Or just:

var result = task.Result; // implicit wait
Console.WriteLine(result);

This allows you to seamlessly write async code. Or in C# 5.0, seamlessly write continuations:

var result = await task; // continuation - this is **not** a wait
Console.WriteLine(result);

As David pointed out, the Invoke method is probably what you want, but if you're looking to write you're own variant, you just need to type cast the value to the generic (T, in your example) to satisfy your comment.

return (T) iar;

Following from the comments,

There are 3 models of Asyncronous development in .NET

APM - (BeginXXX EndXXX) Which you are using here, when the long running task completes it calls back into your code in the EndXXX method

EAP - Event based. In this model, when the long running task completes, an event is raised to inform your code.

TPL - New in .NET 4, this is the 'Task' based version. it looks most like Syncronous programming to client code, using a fluent interface. Its calls back to your code using continueWith.

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!