如果收到新请求,如何取消上一个任务?

lbr*_*him 2 c# task task-parallel-library windows-runtime dotnet-httpclient

我会尽量简化我的情况,使其更加简洁明了.所以,我正在开发一个WinRT应用程序,用户在2秒钟后输入文本,TextBox并在其TextChanged事件中,我需要根据用户文本发出远程请求来获取数据.

现在,用户输入文本并初始化了Web请求,但用户立即写入另一个术语.所以,我需要取消第一个Web请求并启动新的请求.

请将以下内容视为我的代码:

private CancellationTokenSource cts;

public HomePageViewModel()
{
    cts = new CancellationTokenSource();
}

private async void SearchPeopleTextChangedHandler(SearchPeopleTextChangedEventArgs e)
{
    //Cancel previous request before making new one        

    //GetMembers() is using simple HttpClient to PostAsync() and get response
    var members = await _myService.GetMembers(someId, cts.Token);

    //other stuff based on members
}
Run Code Online (Sandbox Code Playgroud)

我知道CancellationToken在这里发挥作用,但我无法弄清楚如何.

Ste*_*ary 7

你已经差不多了.核心思想是单个CancellationTokenSource只能被取消一次,因此必须为每个操作创建一个新的.

private CancellationTokenSource cts;

private async void SearchPeopleTextChangedHandler(SearchPeopleTextChangedEventArgs e)
{
  // If there's a previous request, cancel it.
  if (cts != null)
    cts.Cancel();

  // Create a CTS for this request.
  cts = new CancellationTokenSource();

  try
  {
    var members = await _myService.GetMembers(someId, cts.Token);

    //other stuff based on members
  }
  catch (OperationCanceledException)
  {
    // This happens if this operation was cancelled.
  }
}
Run Code Online (Sandbox Code Playgroud)