只需停止异步方法
本文关键字:异步方法 | 更新日期: 2023-09-27 18:05:58
我有一个方法,当用户点击屏幕时播放声音,&我想让它在用户再次点击屏幕时停止播放。但问题是"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;
}
使用CancellationToken而不抛出异常的另一种方法是声明/初始化CancellationTokenSource cts并传递cts。就像上面Stephen Cleary的回答一样,Token to DoSomething。
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;
}