Timeout an async method implemented with TaskCompletionSource

You could use CancellationTokenSource with timeout. Use it together with your TaskCompletionSource like this. E.g.: public Task<OpResult> BlackBoxOperationAysnc() { var tcs = new TaskCompletionSource<TestResult>(); const int timeoutMs = 20000; var ct = new CancellationTokenSource(timeoutMs); ct.Token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: false); EventHandler<EndOpEventArgs> eventHandler = (sender, args) => { … tcs.TrySetResult(OpResult.BlarBlar); } blackBox.EndAsyncOpEvent += eventHandler; blackBox.StartAsyncOp(); return tcs.Task; … Read more

How to combine TaskCompletionSource and CancellationTokenSource?

If I understand you correctly, you can do it like this: using (cancellationToken.Register(() => { // this callback will be executed when token is cancelled task_comletion_source.TrySetCanceled(); })) { // … await task_comletion_source.Task; } Note that it will throw an exception on your await, which you have to handle.

When should TaskCompletionSource be used?

I mostly use it when only an event based API is available (for example Windows Phone 8 sockets): public Task<Args> SomeApiWrapper() { TaskCompletionSource<Args> tcs = new TaskCompletionSource<Args>(); var obj = new SomeApi(); // will get raised, when the work is done obj.Done += (args) => { // this will notify the caller // of the … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)