如何取消异步等待
Posted 碎心炼心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何取消异步等待相关的知识,希望对你有一定的参考价值。
首先先建一个扩展方法
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 }
以上是关于如何取消异步等待的主要内容,如果未能解决你的问题,请参考以下文章
在 useEffect 挂钩中取消所有异步/等待任务以防止反应中的内存泄漏的正确方法是啥?