代码之家  ›  专栏  ›  技术社区  ›  User987

执行并行时布尔包含任务取消异常。C中的Foreach#

  •  1
  • User987  · 技术社区  · 7 年前

    Message :One or more errors occurred.<br/>
    StackTrace :   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
       at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body)
    

    Parllel.Foreach(_collection, new ParallelOptions { MaxDegreeOfParallelism =5 }, item=>
    {
    // code inside
    });
    

    这个问题的根源可能是什么?你们有什么建议吗?我该去哪里找?

      string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Error.txt";
    
                using (StreamWriter writer = new StreamWriter(filePath, true))
                {
                    writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                       "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                    writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Ehsan Sajjad    7 年前

    拟议的日志更改:

    string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Error.txt";
    
    using (StreamWriter writer = new StreamWriter(filePath, true))
    {
          foreach(var inner in (ex as AggregateException).?InnerExceptions ?? (new [] {ex}))
          {
               writer.WriteLine("Message :" + inner.Message + "<br/>" + Environment.NewLine + "StackTrace :" + inner.StackTrace +
               "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
               writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
          }
    }
    
        2
  •  1
  •   Nitram    7 年前

    你的 // code inside Parallel.For 循环终止其工作任务以正确关闭。通常 ForEach 作用