【发布时间】:2021-12-24 18:51:07
【问题描述】:
我尝试通过带有计时器的 CancellationToken 来停止进程。
但 IsCancellationRequested 始终为 false。
我尝试拨打cancellationToken.ThrowIfCancellationRequested(); 不起作用。
public async Task<IReadOnlyList<ISearchableDevice>> SearchAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(100, cancellationToken);
cancellationToken.ThrowIfCancellationRequested(); // doesn't work
}
IReadOnlyList<ISearchableDevice> devices = new List<ISearchableDevice>();
return devices;
}
private void OnStartSearchCommandExecuted(object? p)
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
{
try
{
InProgress = true;
DeviceSearcher.SearchAsync(cts.Token)
.ContinueWith(task =>
{
InProgress = false;
}, cts.Token);
}
catch (Exception)
{
// TODO: Add exception handling
}
}
}
错在哪里?
【问题讨论】:
-
尝试在
SearchAsync调用中使用await而不是ContinueWith。现在你的cts在超时之前就被处理掉了。 -
@Serg 我认为你是对的,但我应该使用 async void,因为我的命令不是异步的
-
@Serg 你是对的。谢谢你。你可以填写答案
-
“但我应该使用 async void,因为” - 结束该句子的正确方法非常少。几乎任何时候你输入“async void”,你都在制造一个问题。
-
@Joshua 没有任何改变
标签: c# cancellationtokensource