taskcompletionsource

Timeout an async method implemented with TaskCompletionSource

試著忘記壹切 提交于 2019-11-28 05:56:41
I have a blackbox object that exposes a method to kick of an async operation, and an event fires when the operation is complete. I have wrapped that into an Task<OpResult> BlackBoxOperationAysnc() method using TaskCompletionSource - that works well. However, in that async wrapper I'd like to manage completing the async call with a timeout error if the event is not received after a given timeout. Currently I manage it with a timer as: public Task<OpResult> BlackBoxOperationAysnc() { var tcs = new TaskCompletionSource<TestResult>(); const int timeoutMs = 20000; Timer timer = new Timer(_ => tcs

When should TaskCompletionSource<T> be used?

巧了我就是萌 提交于 2019-11-26 12:38:07
AFAIK, all it knows is that at some point, its SetResult or SetException method is being called to complete the Task<T> exposed through its Task property. In other words, it acts as the producer for a Task<TResult> and its completion. I saw here the example : If I need a way to execute a Func asynchronously and have a Task to represent that operation. public static Task<T> RunAsync<T>(Func<T> function) { if (function == null) throw new ArgumentNullException(“function”); var tcs = new TaskCompletionSource<T>(); ThreadPool.QueueUserWorkItem(_ => { try { T result = function(); tcs.SetResult

When should TaskCompletionSource<T> be used?

ε祈祈猫儿з 提交于 2019-11-26 02:40:07
问题 AFAIK, all it knows is that at some point, its SetResult or SetException method is being called to complete the Task<T> exposed through its Task property. In other words, it acts as the producer for a Task<TResult> and its completion. I saw here the example : If I need a way to execute a Func asynchronously and have a Task to represent that operation. public static Task<T> RunAsync<T>(Func<T> function) { if (function == null) throw new ArgumentNullException(“function”); var tcs = new