我有这种播放声音的方法,当用户点击屏幕时,&当用户再次点击屏幕时,我希望它停止播放。但问题是“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;
}
任何帮助将不胜感激 谢谢:))
答案 0 :(得分:26)
这是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;
}
答案 1 :(得分:0)
在不引发异常的情况下使用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;
}