【问题标题】:C#5 async method completed event.C#5 异步方法完成事件。
【发布时间】:2012-11-23 15:19:56
【问题描述】:
我有一个这样的异步方法
public async void Method()
{
await // Long run method
}
当我调用这个方法时,我可以在这个方法完成时有一个事件吗?
public void CallMethod()
{
Method();
// Here I need an event once the Method() finished its process and returned.
}
【问题讨论】:
标签:
c#
asynchronous
.net-4.5
async-await
c#-5.0
【解决方案1】:
你为什么需要它?需要等待完成吗?像这样工作:
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
}
如果您不能使用 await 并且确实需要使用类似事件的模式,请使用 ContinueWith。您可以将其视为为任务完成添加事件处理程序。