我有返回一些数据类型的方法
MyType MyMethod()
如果我将此方法运行到一个单独的线程中,如何在调用线程(调用其他线程执行 MyMethod)中检索此返回类型?
有很多种方法,这里是一个:
Func<MyType> func = MyMethod;
func.BeginInvoke(ar =>
{
MyType result = (MyType)func.EndInvoke(ar);
// Do something useful with result
...
},
null);
这是另一个,使用 Task
API:
Task.Factory
.StartNew(new Func<MyType>(MyMethod))
.ContinueWith(task =>
{
MyType result = task.Result;
// Do something useful with result
...
});
最后一个,使用异步 CTP(C# 5 预览版):
MyType result = await Task.Factory.StartNew<MyType>(MyMethod);
// Do something useful with result
...
我是一名优秀的程序员,十分优秀!