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