嗨,我一直在论坛上阅读很多,但我无法找到问题的答案......
这是我想要在布尔值变为TRUE时取消的函数:
Task<PortalODataContext> task = Task.Factory.StartNew(() =>
{
var context = connection.ConnectToPortal();
connection.ListTemplateLib = this.ShellModel.ConnectionManager.GetTemplateLibrarys(connection);
connection.ListTemplateGrp = this.ShellModel.ConnectionManager.GetTemplateGroups(connection, connection.TemplateLibraryId);
connection.ListTemplates = this.ShellModel.ConnectionManager.GetTemplates(connection, connection.TemplateGroupId);
return context;
}, token);
如何在没有LOOP的情况下验证令牌是否收到取消请求?
类似的东西:
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancelled before long running task started");
return;
}
for (int i = 0; i <= 100; i++)
{
//My operation
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancelled");
break;
}
}
但我没有需要循环的操作,所以我不知道该怎么做......
答案 0 :(得分:4)
我假设token
是CancellationToken
?
您不需要循环,而是查看CancellationToken.ThrowIfCancellationRequested。通过调用它,CancellationToken
类将检查它是否已被取消,并通过抛出异常来终止任务。
您的任务代码将转变为:
using System.Threading.Tasks;
Task.Factory.StartNew(()=>
{
// Do some unit of Work
// .......
// now check if the task has been cancelled.
token.ThrowIfCancellationRequested();
// Do some more work
// .......
// now check if the task has been cancelled.
token.ThrowIfCancellationRequested();
}, token);
如果抛出取消异常,则从Task.Factory.StartNew
返回的任务将设置其IsCanceled属性。如果您正在使用async / await,则需要捕获OperationCanceledException
并正确清理。
查看MSDN上的Task Cancellation页面了解详情。