与前面的代码for class RulyCanceler相比,我希望使用CancellationTokenSource
来运行代码。
如何像Cancellation Tokens中提到的那样使用它,即不抛出/捕获异常?我可以使用IsCancellationRequested
属性吗?
我尝试这样使用它:
cancelToken.ThrowIfCancellationRequested();
和
try
{
new Thread(() => Work(cancelSource.Token)).Start();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
}
但这在Work(CancellationToken cancelToken)
方法中的cancelToken.ThrowIfCancellationRequested();
上产生了一个运行时错误:
System.OperationCanceledException was unhandled
Message=The operation was canceled.
Source=mscorlib
StackTrace:
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at _7CancellationTokens.Token.Work(CancellationToken cancelToken) in C:\xxx\Token.cs:line 33
at _7CancellationTokens.Token.<>c__DisplayClass1.<Main>b__0() in C:\xxx\Token.cs:line 22
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
我成功运行的代码捕获了新线程中的OperationCanceledException:
using System;
using System.Threading;
namespace _7CancellationTokens
{
internal class Token
{
private static void Main()
{
var cancelSource = new CancellationTokenSource();
new Thread(() =>
{
try
{
Work(cancelSource.Token); //).Start();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
}
}).Start();
Thread.Sleep(1000);
cancelSource.Cancel(); // Safely cancel worker.
Console.ReadLine();
}
private static void Work(CancellationToken cancelToken)
{
while (true)
{
Console.Write("345");
cancelToken.ThrowIfCancellationRequested();
}
}
}
}
发布于 2017-07-24 09:37:09
你可以创建一个带有取消令牌的任务,当你应用转到后台时,你可以取消这个令牌。
您可以在PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle中执行此操作
var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
await Task.Delay(10000);
// call web API
}, cancelToken.Token);
//this stops the Task:
cancelToken.Cancel(false);
另一种解决方案是Xamarin.Forms中的用户定时器,当应用程序转到后台https://xamarinhelp.com/xamarin-forms-timer/时停止定时器
https://stackoverflow.com/questions/15067865
复制相似问题