码迷,mamicode.com
首页 > 其他好文 > 详细

如何取消异步等待

时间:2017-10-17 15:45:54      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:pre   div   log   scom   async   source   try   ever   扩展方法   

首先先建一个扩展方法

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 
}

  

如何取消异步等待

标签:pre   div   log   scom   async   source   try   ever   扩展方法   

原文地址:http://www.cnblogs.com/karl-F/p/7681098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!