Ala*_*an2 1 c# multithreading task cancellationtokensource
我有创建 CancellationTokenSource 并将其传递给方法的代码。
我在另一个发出 cts.Cancel(); 的应用程序中有代码。
有没有一种方法可以使该方法立即停止,而不必等待 while 循环内的两行完成?
请注意,如果它导致我可以处理的异常,我会没事的。
public async Task OnAppearing()
{
cts = new CancellationTokenSource();
await GetCards(cts.Token);
}
public async Task GetCards(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
App.viewablePhrases = App.DB.GetViewablePhrases(Settings.Mode, Settings.Pts);
await CheckAvailability();
}
}
Run Code Online (Sandbox Code Playgroud)
What I can suggest:
至于你的功能,我不知道它们在内部究竟是如何工作的。但是让我们假设您在其中一个内部有一个长时间运行的迭代:
CheckAvailability(CancellationToken ct)
{
for(;;)
{
// if cts.Cancel() was executed - this method throws the OperationCanceledException
// if it wasn't the method does nothing
ct.ThrowIfCancellationRequested();
...calculations...
}
}
Run Code Online (Sandbox Code Playgroud)
或者,假设您要访问其中一个函数内的数据库,并且您知道此过程将需要一段时间:
CheckAvailability(CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
AccessingDatabase();
}
Run Code Online (Sandbox Code Playgroud)
这不仅会阻止您的函数继续执行,还会将执行者任务状态设置为 TaskStatus.Canceled
并且不要忘记捕获异常:
public async Task GetCards(CancellationToken ct)
{
try
{
App.viewablePhrases = App.DB.GetViewablePhrases(Settings.Mode, Settings.Pts, ct);
await CheckAvailability(ct);
}
catch(OperationCanceledException ex)
{
// handle the cancelation...
}
catch
{
// handle the unexpected exception
}
}
Run Code Online (Sandbox Code Playgroud)