gpt4 book ai didi

c# - 简单地停止异步方法

转载 作者:可可西里 更新时间:2023-11-01 08:53:47 26 4
gpt4 key购买 nike

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

关于c# - 简单地停止异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15614991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com