【问题标题】: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。您可以将其视为为任务完成添加事件处理程序。

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多