处理Windows 8.1应用程序中的长异步操作和频繁事件

时间:2014-06-06 15:37:09

标签: c# event-handling async-await

请考虑以下事项:

  void event_handler(object sender, ...){
     DoSomething();
  }

  void DoSomething(){
     // change some page's state 
     // change some page's private members
     var someData = await LongOperation();
     // change some page's state 
     // change some page's private members
  }

现在,我想要以下行为:如果在前一个LongOperation()尚未完成时触发event_handler,则必须取消这样的LongOperation()。

执行此操作的最简单和首选方法是什么?

1 个答案:

答案 0 :(得分:3)

取消最好通过CancellationToken

处理
private CancellationTokenSource _cts;
async void event_handler()
{
  if (_cts != null)
    _cts.Cancel();
  _cts = new CancellationTokenSource();
  await DoSomethingAsync();
}

async Task DoSomethingAsync()
{
  // change some page's state 
  // change some page's private members
  var someData = await LongOperationAsync(_cts.Token);
  // change some page's state 
  // change some page's private members
}

有各种优化,即如果先前的操作未被取消,则重用先前的CancellationTokenSource,但此代码说明了一般原则。