TaskCompletionSource : When to use SetResult() versus TrySetResult(), etc

后端 未结 1 1399
孤城傲影
孤城傲影 2021-02-06 20:45

I\'m trying to wrap my head around the TPL, the new async / await features in C# 5, and the mysteries of TaskCompletionSource.

One

相关标签:
1条回答
  • 2021-02-06 21:23

    I suspect the point is that if there's only one thing which will be setting the result, just call SetResult etc. If you end up calling SetResult twice, that indicates a bug. (Likewise if the TaskCompletionSource has been disposed.)

    If you've got several threads which could all be trying to set the result at the same time (e.g. it's there to indicate the first result out of several parallel web service calls) then use TrySetResult, as it's entirely reasonable for multiple threads to "try" to set the result, unaware of whether another thread has already set it.

    I've not seen any official guidance on it, but that would make sense.

    0 讨论(0)
提交回复
热议问题