C# 简单地停止异步方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15614991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:22:57  来源:igfitidea点击:

simply stop an async method

c#windows-phoneasync-await

提问by Jaydeep Solanki

I have this method which plays a sound, when the user taps on the screen, & I want it to stop playing it when the user taps the screen again. But the problem is "DoSomething()" method doesn't stop, it keeps going till it finishes.

我有这种播放声音的方法,当用户点击屏幕时,我希望它在用户再次点击屏幕时停止播放。但问题是“DoSomething()”方法不会停止,它会一直运行直到完成。

bool keepdoing = true;

private async void ScreenTap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        keepdoing = !keepdoing;
        if (!playing) { DoSomething(); }
    }

private async void DoSomething() 
    {
        playing = true;
        for (int i = 0; keepdoing ; count++)
        {
            await doingsomething(text);
        }
        playing = false;
    }

Any help will be appreciated.
Thanks :)

任何帮助将不胜感激。
谢谢 :)

采纳答案by Stephen Cleary

This is what a CancellationTokenis for.

这就是 aCancellationToken的用途。

CancellationTokenSource cts;

private async void ScreenTap(object sender, System.Windows.Input.GestureEventArgs e)
{
  if (cts == null)
  {
    cts = new CancellationTokenSource();
    try
    {
      await DoSomethingAsync(cts.Token);
    }
    catch (OperationCanceledException)
    {
    }
    finally
    {
      cts = null;
    }
  }
  else
  {
    cts.Cancel();
    cts = null;
  }
}

private async Task DoSomethingAsync(CancellationToken token) 
{
  playing = true;
  for (int i = 0; ; count++)
  {
    token.ThrowIfCancellationRequested();
    await doingsomethingAsync(text, token);
  }
  playing = false;
}

回答by abhigdeal

Another way to use CancellationToken without throwing exceptions would be to declare/initialize CancellationTokenSource cts and pass cts.Token to DoSomething as in Stephen Cleary's answer above.

在不抛出异常的情况下使用 CancellationToken 的另一种方法是声明/初始化 CancellationTokenSource cts 并将 cts.Token 传递给 DoSomething,如上面 Stephen Cleary 的回答。

private async void DoSomething(CancellationToken token) 
{
    playing = true;
    for (int i = 0; keepdoing ; count++)
    {
        if(token.IsCancellationRequested)
        {
         // Do whatever needs to be done when user cancels or set return value
         return;
        }
        await doingsomething(text);
    }
    playing = false;
}