zoukankan      html  css  js  c++  java
  • 如何取消异步等待

    首先先建一个扩展方法

    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 
    }
    

      

  • 相关阅读:
    移动端调试Vconsole
    Vue-返回顶部
    Vue-封装loading
    Vue-水印封装
    Vue-封装scroll触底
    微信小程序-图片上传
    前端面试题(2)
    前端常见面试题
    服务端渲染(SSR)和客户端(CSR)渲染的区别
    什么是模块化?模块化开发的好处
  • 原文地址:https://www.cnblogs.com/karl-F/p/7681098.html
Copyright © 2011-2022 走看看