有没有办法让我运行的方法立即停止使用cts.Cancel();? [英] Is there a way I can cause a running method to stop immediately with a cts.Cancel();
问题描述
我有创建CancellationTokenSource并将其传递给方法的代码.
I have code that creates a CancellationTokenSource and that passes it to a method.
我在另一个发布cts.Cancel()的应用程序中都有代码.
I have code in another are of the app that issues a cts.Cancel();
有没有一种方法可以使该方法立即停止,而不必等待while循环中的两行完成?
Is there a way that I can cause that method to stop immediately without me having to wait for the two lines inside the while loop to finish?
请注意,如果它引起了我可以处理的异常,那我就可以了.
Note that I would be okay if it caused an exception that I could handle.
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();
}
}
推荐答案
我的建议:
- 修改GetViewablePhrases和CheckAvailability,以便您可以将CancellationToken传递给它们;
- 使用 ct.ThrowIfCancellationRequested()在这些函数中;
- 尝试/捕获GetCards中的OperationCanceledException;
关于您的功能,我不知道它们在内部的工作原理.但让我们假设您在其中一个内部有一个长期运行的迭代:
As for your your functions I don't know how exactly they work inside. But let's assume you have a long running iteration inside one of them:
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...
}
}
或者说您要在其中一个函数中访问数据库,并且您知道此过程将花费一些时间:
Or let's say you are going to access your database inside one of the function and you know that this process is going to take a while:
CheckAvailability(CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
AccessingDatabase();
}
这不仅会阻止您的函数继续执行,还会将执行者的任务状态设置为TaskStatus.Canceled
This will not only prevent your functions from proceeding with execution, this also will set the executioner Task status as 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
}
}
这篇关于有没有办法让我运行的方法立即停止使用cts.Cancel();?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!