I want to use TaskCompletionSource
to wrap MyService
which is a simple service:
public static Task ProcessAsync(MyService
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)