防止两提交同一异步任务

async  Task  Button1Click()
{
 // Assume we're being called on UI thread... if not, the two assignments must be made atomic.
// Note: we factor out "FooHelperAsync" to avoid an await between the two assignments.
    // without an intervening await. 
     if  (FooAsyncCancellation !=  null ) FooAsyncCancellation.Cancel();
     FooAsyncCancellation  =  new  CancellationTokenSource ();
     FooAsyncTask  = FooHelperAsync(FooAsyncCancellation.Token);

     await  FooAsyncTask;
}

 Task  FooAsyncTask;
 CancellationTokenSource  FooAsyncCancellation;
 
 async  Task  FooHelperAsync( CancellationToken  cancel)
{
     try  {  if  (FooAsyncTask !=  null )  await  FooAsyncTask; }
     catch  ( OperationCanceledException ) { }
    cancel.ThrowIfCancellationRequested();
     await  FooAsync(cancel);
}

 async  Task  FooAsync( CancellationToken  cancel)
{
    ...
}

 

posted on 2015-07-24 21:33  武胜-阿伟  阅读(277)  评论(0编辑  收藏  举报