TaskCompletionSource throws “An attempt was made to transition a task to a final state when it had already completed”

后端 未结 3 1366
粉色の甜心
粉色の甜心 2021-02-07 08:06

I want to use TaskCompletionSource to wrap MyService which is a simple service:

public static Task ProcessAsync(MyService         


        
3条回答
  •  天命终不由人
    2021-02-07 08:53

    An alternative solution to i3arnon's answer would be:

    public async static Task ProcessAsync(MyService service, int parameter)
    {
        var tcs = new TaskCompletionSource();
    
        EventHandler callback = 
            (s, e) => tcs.SetResult(e.Result);
    
        try
        {
            contacts.Completed  += callback;
    
            contacts.RunAsync(parameter);
    
            return await tcs.Task;
        }
        finally
        {
            contacts.Completed  -= callback;
        }
    }
    

    However, this solution will have a compiler generated state machine. It will use more memory and CPU.

提交回复
热议问题