如何使用异步方法同时执行两个方法,然后等待1个finalize方法继续执行?
public class Foo{
public async Task<string> Method1()
{
//run a task
return result;
}
public async void Method2(string result)
{
//do some work
//do some work
//do some work
//wait for method1
//do something with result
}
}
Foo foo = new Foo();
var result = await foo.Method1();
foo.Method2(result);
答案 0 :(得分:3)
在样本中分别调用Method1和Method2(Method2不知道Method1)的情况下-通过将{1}传递给Method2,您将获得所需的行为。
public class Service
{
public async Task<string> MethodOne()
{
// do something
var result = await CalculateSomeResult();
return result;
}
public async Task MethodTwo(Task<string> task)
{
// do some work
// do some work
var methodOneResult = await task;
// do something with the result of methodOne
}
}
用法
var service = new Service();
var methodOneTask = service.methodOne();
await service.MethodTwo(methodOneTask);
答案 1 :(得分:1)
您可以使用EventWaitHandle
:
public class Sequence {
EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
public async Task Tsk1() {
Console.WriteLine("Did some work from tsk1");
handle.Set();
}
public async Task Tsk2() {
handle.WaitOne();
Console.WriteLine("Doing work after tsk1 finished");
//do some other stuff
}
}
class Program {
static async Task Main(string[] args) {
Sequence seq = new Sequence();
var t2 =Task.Run(seq.Tsk2);
var t1 =Task.Run(seq.Tsk1);
await Task.WhenAll(t1, t2);
Console.WriteLine("finished both");
}
}
答案 2 :(得分:-1)
如果我对您的理解正确,则需要Method2才能使用Method1返回的结果-也就是说,您需要从Method1内部调用Method2,而不是在它之后:
public class Foo{
public async Task<string> Method1()
{
//run a task
return result;
}
public async void Method2(string result)
{
//do some work
//do some work
//do some work
var intermediaryResult = await Method1();
//do something with result
}
}
Foo foo = new Foo();
await foo.Method2(result);
(此外,您还必须等待Method2-它们都是异步的)
请注意,您应该never have async void methods unless you have no choice-因此Method2应该返回Task。
答案 3 :(得分:-1)
怎么样?
public async Task<string> Method2()
{
//do some work
//do some work
//do some work
var result = await foo.Method1();
//do something with result
return result;
}
Foo foo = new Foo();
var result = await foo.Method2();
(半)并行执行:
public async Task<string> Method2()
{
var task1 = foo.Method1();
//do some work
//do some work
//do some work
var result = await task1;
//do something with result
return result;
}
答案 4 :(得分:-2)
public class Foo
{
public async Task<string> Method1()
{
//run a task
return result;
}
public async void Method2(string result)
{
//do some work
//do some work
//do some work
//wait for method1
//do something with result
}
}
await Task.Run(()=>
{
Foo foo = new Foo();
var result = foo.Method1();
foo.Method2(result);
});