Sen*_*ncy 3 c# asynchronous async-await c#-5.0 .net-4.5
我有一个像这样的异步方法
public async void Method()
{
await // Long run method
}
Run Code Online (Sandbox Code Playgroud)
当我调用此方法时,我可以在此方法完成时发生事件吗?
public void CallMethod()
{
Method();
// Here I need an event once the Method() finished its process and returned.
}
Run Code Online (Sandbox Code Playgroud)
你为什么需要那个?你需要等待完成吗?这样工作:
public async Task Method() //returns Task
{
await // Long run method
}
public void CallMethod()
{
var task = Method();
//here you can set up an "event handler" for the task completion
task.ContinueWith(...);
await task; //or await directly
}
Run Code Online (Sandbox Code Playgroud)
如果你不能使用await并且确实需要使用类似事件的模式,请使用ContinueWith.您可以将其视为为任务完成添加事件处理程序.