c# – 只是停止异步方法

前端之家收集整理的这篇文章主要介绍了c# – 只是停止异步方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这种播放声音的方法,当用户点击屏幕时,&当用户再次点击屏幕时,我希望它停止播放.但问题是“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;
    }

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

解决方法

这是一个CancellationToken是什么.
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;
}
原文链接:https://www.f2er.com/csharp/95103.html

猜你在找的C#相关文章