c# – 使用Task的TaskCanceledException
发布时间:2020-12-15 23:26:09  所属栏目:百科  来源:网络整理 
            导读:我正在做的事情的概述:在一个循环中,我正在开始一个新的任务 string并将其添加到列表 Task string.问题是,在返回字符串后,任务抛出System.Threading.Tasks.TaskCanceledException,我不知道为什么.下面是我正在做的修剪版本 public async Taskstring Generat
                
                
                
            | 
 我正在做的事情的概述:在一个循环中,我正在开始一个新的任务< string>并将其添加到列表< Task< string>>.问题是,在返回字符串后,任务抛出System.Threading.Tasks.TaskCanceledException,我不知道为什么.下面是我正在做的修剪版本 
  
  
  public async Task<string> GenerateXml(object item)
{
    using (var dbContext = new DatabaseContext())
    {
        //...do some EF dbContext async calls here
        //...generate the xml string and return it
        return "my xml data";
    }
}
var tasks = new List<Task<string>>();我的循环看起来像: foreach (var item in items)
{
    tasks.Add(Task.Run(() => GenerateXml(item).ContinueWith((t) => { return ""; },TaskContinuationOptions.OnlyOnFaulted)));
    //also tried: 
    tasks.Add(Task.Run(async () => await GenerateXml(item).ContinueWith((t) => { return ""; },TaskContinuationOptions.OnlyOnFaulted)));
    //both generate the same exception
    //after looking at my code,I was using the ContinueWith on the GenerateXml method call,which should still work,right?
    //I moved the continue with to the `Task.Run` and still get the exception.
}
Task.WaitAll(tasks.ToArray()); //this throws the AggregateException which contains the TaskCanceledException当我单步执行代码时,它会返回“my xml data”;但抛出异常. 我想用ContinueWith避免的是当我循环每个任务并获得结果时,它不会抛出与WaitAll抛出的相同的AggregateException. 这是一个工作的控制台应用程序抛出…我知道问题是与ContinueWith,但为什么? class Program
{
    static void Main(string[] args)
    {
        var program = new Program();
        var tasks = new List<Task<string>>();
        tasks.Add(Task.Run(() => program.GenerateXml().ContinueWith((t) => { return ""; },TaskContinuationOptions.OnlyOnFaulted)));
        Task.WaitAll(tasks.ToArray()); //this throws the AggregateException
        foreach (var task in tasks)
        {
            Console.WriteLine(task.Result);
        }
        Console.WriteLine("finished");
        Console.ReadKey();
    }
    public async Task<string> GenerateXml()
    {
        System.Threading.Thread.Sleep(3000);
        return "my xml data";
    }
}解决方法
 您正在运行第二个任务. 
  .ContinueWith((t)任务. 要运行正确的,您需要重构代码. Task<string> t1 = Task.Run(() => program.GenerateXml());
    t1.ContinueWith((t) => { return ""; },TaskContinuationOptions.OnlyOnFaulted);
    tasks.Add(t1);您可以重构这样的任务:(用于错误处理) tasks.Add(program.GenerateXml().ContinueWith(t => {return t.IsFaulted? "": t.Result; }));(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
