防止两提交同一异步任务

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)
{
    ...
}
原文地址:https://www.cnblogs.com/zeroone/p/4674715.html