Ale*_*ndr 2 c# windows-phone-7 async-await windows-phone-8
我有一个功能:
int f1(int a)
{
return a;
}
int f2(int a)
{
return a*2;
}
Run Code Online (Sandbox Code Playgroud)
我希望执行函数异步和并行,等待结果和求和然后结果.我可以使用代码
var result1 = Task.Run(() => f1(5));
var result2 = Task.Run(() => f2(10));
await Task.WhenAll(result1, result2);
int result = result1.Result + result2.Result;
Run Code Online (Sandbox Code Playgroud)
这很酷.但是,如果我的函数与回调一起工作,那该怎么做呢
void f1(Action<int> action, int a)
{
action.Invoke(a);
}
void f2(Action<int> action, int a)
{
a = a*2;
action.Invoke(a);
}
f1(result => Console.WriteLine("result1 = {0}", result), 5);
f2(result => Console.WriteLine("result2 = {0}", result), 10);
Run Code Online (Sandbox Code Playgroud)
我无法重写这个函数,这个函数在其他代码中使用.在这种情况下,我可以解决我的代码不像地狱的问题?
var tcs1 = new TaskCompletionSource<int>();
var tcs2 = new TaskCompletionSource<int>();
f1( (x) => { tcs1.SetResult(x); }, 5);
f2( (x) => { tcs2.SetResult(x); }, 10);
var results = await Task.WhenAll(tcs1.Task, tcs2.Task);
int result = results[0] + results[1];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |