C# 如何取消没有循环的任务
嗨,我在论坛上读了很多,但是我找不到我问题的答案 以下是布尔值变为TRUE时要取消的函数:C# 如何取消没有循环的任务,c#,async-await,cancellation-token,C#,Async Await,Cancellation Token,嗨,我在论坛上读了很多,但是我找不到我问题的答案 以下是布尔值变为TRUE时要取消的函数: Task<PortalODataContext> task = Task.Factory.StartNew(() => { var context = connection.ConnectToPortal(); connection.ListTemplateLib = this.ShellModel.ConnectionMa
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);
Task Task=Task.Factory.StartNew(()=>
{
var context=connection.ConnectToPortal();
connection.ListTemplateLib=this.ShellModel.ConnectionManager.GetTemplateLibrary(连接);
connection.ListTemplateGrp=this.ShellModel.ConnectionManager.GetTemplateGroups(connection,connection.TemplateLibraryId);
connection.ListTemplates=this.ShellModel.ConnectionManager.GetTemplates(connection,connection.TemplateGroupId);
返回上下文;
},代币);
如何验证令牌是否在没有循环的情况下收到取消请求
诸如此类:
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;
}
}
if(token.iscancellationrequest)
{
Console.WriteLine(“在长时间运行的任务开始之前取消”);
返回;
}
对于(inti=0;i我假设token
是CancellationToken
您不需要循环,而是查看一下。通过调用它,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
返回的任务将设置其属性。如果使用async/await,则需要捕获OperationCanceledException
并适当清理
查看MSDN上的页面了解更多信息。为什么不添加循环,以便我们按照您的思路进行操作。在每次粒度操作后测试取消是否需要验证令牌在每行之后是否被取消?在每个工作单元之后,取消是有意义的。可以是单个方法调用或一组方法调用。使用在您发布的示例中,我会在每个ConnectionManager调用之前进行检查。它并不总是每一行代码。