17

我有这种方法可以在用户点击屏幕时播放声音,并且我希望它在用户再次点击屏幕时停止播放。但问题是“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;
    }

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

4

2 回答 2

29

这就是 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;
}
于 2013-03-25T12:50:44.547 回答
5

使用 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;
}
于 2018-11-09T02:04:23.227 回答