Timeout an async method implemented with TaskCompletionSource
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