如何取消的await任务? [英] How to cancel a Task in await?

查看:253
本文介绍了如何取消的await任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我玩这些Windows 8的WinRT的任务,我想用下面的方法来取消任务,和它的作品的某个位置。该CancelNotification方法不会被调用,它让你觉得任务被取消,但会在后台任务保持运行,它的建成在此之后,任务的状态始终完成并从未取消。有没有办法完全停止时,它取消了任务?

 专用异步无效TryTask()
{
    CancellationTokenSource源=新CancellationTokenSource();
    source.Token.Register(CancelNotification);
    source.CancelAfter(TimeSpan.FromSeconds(1));
    变种任务=任务&所述; INT> .Factory.StartNew(()=> slowFunc(1,2),source.Token);    等待任务;    如果(task.IsCompleted)
    {
        MessageDialog MD =新MessageDialog(task.Result.ToString());
        等待md.ShowAsync();
    }
    其他
    {
        MessageDialog MD =新MessageDialog(楼花);
        等待md.ShowAsync();
    }
}私人诠释slowFunc(INT A,INT B)
{
    字符串someString =的String.Empty;
    的for(int i = 0; I< 200000;我++)
    {
        someString + =一个;
    }    返回A + B;
}私人无效CancelNotification()
{
}


解决方案

取消(这是引入.NET 4.0,是自那时以来大致维持不变)和基于任务的异步模式,它提供了有关如何使用的CancellationToken 异步方法的指导方针。

要总结,你传递一个的CancellationToken 到支持取消的每个方法,并且该方法必须定期检查它。

 专用异步任务TryTask()
{
  CancellationTokenSource源=新CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  任务< INT>任务= Task.Run(()=> slowFunc(1,2,source.Token),source.Token);  //(已取消的任务等待时会生成除外)。
  等待任务;
}私人诠释slowFunc(INT A,INT B,的CancellationToken的CancellationToken)
{
  字符串someString =的String.Empty;
  的for(int i = 0; I< 200000;我++)
  {
    someString + =一个;
    如果(I%1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }  返回A + B;
}

I'm playing with these Windows 8 WinRT tasks, and I'm trying to cancel a task using the method below, and it works to some point. The CancelNotification method DOES get called, which makes you think the task was cancelled, but in the background the task keeps running, then after it's completed, the status of the Task is always completed and never cancelled. Is there a way to completely halt the task when it's cancelled?

private async void TryTask()
{
    CancellationTokenSource source = new CancellationTokenSource();
    source.Token.Register(CancelNotification);
    source.CancelAfter(TimeSpan.FromSeconds(1));
    var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token);

    await task;            

    if (task.IsCompleted)
    {
        MessageDialog md = new MessageDialog(task.Result.ToString());
        await md.ShowAsync();
    }
    else
    {
        MessageDialog md = new MessageDialog("Uncompleted");
        await md.ShowAsync();
    }
}

private int slowFunc(int a, int b)
{
    string someString = string.Empty;
    for (int i = 0; i < 200000; i++)
    {
        someString += "a";
    }

    return a + b;
}

private void CancelNotification()
{
}

解决方案

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods.

To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically.

private async Task TryTask()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);

  // (A canceled task will raise an exception when awaited).
  await task;
}

private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
  string someString = string.Empty;
  for (int i = 0; i < 200000; i++)
  {
    someString += "a";
    if (i % 1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }

  return a + b;
}

这篇关于如何取消的await任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆