[使用Task
作为指导,尝试取消并重新启动this时收到此错误。对我来说不清楚的是为什么尽管尝试/捕获,仍然发生错误。
应该发生什么
该代码旨在在用户在1秒钟的延迟后将值输入到文本框中后,运行搜索任务。但是,如果用户在延迟后仍继续输入,我想取消任务并重新启动它。
主窗口中的代码(PMSearch)以启动任务
完成任务的工作。这是代码:
CancellationTokenSource CancellationSource;
Task ActiveTask;
private void SearchTermEntered(object sender, string searchText)
{
...do some stuff
_ = SearchAsync();
}
private async Task SearchAsync()
{
CancelSearch(null,null);
CancellationSource = new CancellationTokenSource();
SearchManager sMan = new SearchManager();
try
{
var searchTask = sMan.SearchPDFAsync(SearchTerm, CancellationSource.Token);
System.Diagnostics.Debug.WriteLine("Starting Task");
var results = await searchTask;
System.Diagnostics.Debug.WriteLine("Results: " + results.ToString());
}
catch (TaskCanceledException ex)
{
System.Diagnostics.Debug.WriteLine("Cancelled: " + ex.Task.ToString());
}
}
取消任务的代码
这是取消任务的处理程序。
private void CancelSearch(object sender, EventArgs e)
{
//Called when user continues to enter text.
CancellationSource?.Cancel();
}
由任务运行的异步代码
public Task<decimal> SearchPDFAsync(string searchTerm, CancellationToken cancellationToken)
{
Task<decimal> task = null;
task = Task.Run(() =>
{
decimal result = 0;
// Loop for a defined number of iterations
for (int i = 0; i < 1000; i++)
{
// HERE IS WHERE I'M TOLD THERE IS AN UNHANDLED EXCEPTION
if (cancellationToken.IsCancellationRequested) throw new TaskCanceledException(task);
// Do something that takes times like a Thread.Sleep in .NET Core 2.
Thread.Sleep(10);
result += i;
}
return result;
});
return task;
}
错误
我在SearchPDFAsync
处收到if (cancellationToken.IsCancellationRequested) throw new TaskCanceledException(task);
中的错误,据我了解,例外是正确的设计模式。尚不清楚的是,当代码嵌套在PMSearch.SearchAsync()
中的try / catch中时,为什么异常被“未处理”。
我在做什么错?
我以此为指导,尝试取消并重新启动任务时收到此错误。我不清楚的是为什么尽管尝试/捕获仍然发生错误。会发生什么代码是...
尝试使用CancellationToken.ThrowIfCancellationRequested();编辑:抱歉,尝试不使用Task.Run();
原始