如何从BeginInvoke返回T值?

我想编写一个类来简化异步编程,比如string s = mylib.BeginInvoek(test,“1”); 这是我的代码:

public T BeginInvokeExWithReturnValue(Func actionFunction) { ExecWithReturnType execWtihReturnValue = new ExecWithReturnType(actionFunction); IAsyncResult iar = execWtihReturnValue.BeginInvoke(new AsyncCallback(EndInvokeExWithReturnValue), execWtihReturnValue); // how to code here to return value } private void EndInvokeExWithReturnValue(IAsyncResult iar) { ExecWithReturnType execWtihReturnValue = (ExecWithReturnType)iar.AsyncState; execWtihReturnValue.EndInvoke(iar); } 

这个BeginInvokeExWithReturnValue函数没有输入参数,但返回一个值,但我不知道如何从BeginInvokeExWithReturnValue函数返回一个值。 任何知道这一点的人,你能帮忙吗? 非常感谢。

你现在要做的不是异步; 如果你想返回 T ,只需使用:

 return actionFunction(); 

这将减少开销。

如果你想要异步,而你是4.0,那么TPL可能是一个不错的选择:

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

现在调用者可以使用:

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

然后在需要时,检查完成,阻止( Wait )完成,注册继续等。或者只是:

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

这允许您无缝地编写异步代码。 或者在C#5.0中,无缝地编写延续:

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

正如David指出的那样,Invoke方法可能就是你想要的,但是如果你想要编写自己的变体,你只需要将值转换为generics(在你的例子中为T)以满足你的注释。

 return (T) iar; 

根据评论,

.NET中有3种Asyncronous开发模型

APM – (BeginXXX EndXXX)您在这里使用的,当长时间运行的任务完成时,它会在EndXXX方法中回调您的代码

EAP – 基于事件。 在此模型中,当长时间运行的任务完成时,将引发一个事件以通知您的代码。

TPL – .NET 4中的新function,这是基于“任务”的版本。 它看起来最像Syncronous编程到客户端代码,使用流畅的界面。 它使用continueWith回调您的代码。

希望这可以帮助