如何取消异步等待
首先先建一个扩展方法
public static async Task<T> WithCancellation<T>( this Task<T> task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); using(cancellationToken.Register( s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) if (task != await Task.WhenAny(task, tcs.Task)) throw new OperationCanceledException(cancellationToken); return await task; }
使用方法:
FileStream fs =...; byte [] b = …; CancellationToken token = …; Task op = fs.ReadAsync(b, 0, b.Length); try { await op.WithCancellation(token); } catch(OperationCanceledException) { op.ContinueWith(t => /* handle eventual completion */); … // whatever you want to do in the case of cancellation }
或者
FileStream fs = …; byte [] b = …; CancellationToken token = …; Task op = fs.ReadAsync(b, 0, b.Length, token); try { await op.WithCancellation(token); } catch(OperationCanceledException) { if (!op.IsCompleted) op.ContinueWith(t => /* handle eventual completion */); … // whatever you want to do in the case of cancellation }
作者:碎心炼心
出处:http://www.cnblogs.com/karl-F
本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。