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

后端 未结 3 1322
粉色の甜心
粉色の甜心 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:42

    It appears that MyService will raise the Completed event more than once. this causes SetResult to be called more than once which causes your error.

    You have 3 options that I see. Change the Completed event to only be raised once (Seems odd that you can complete more than once), change SetResult to TrySetResult so it does not throw a exception when you try to set it a 2nd time (this does introduce a small memory leak as the event still gets called and the completion source still tries to be set), or unsubscribe from the event (i3arnon's answer)

提交回复
热议问题