首页 > 解决方案 > TaskScheduler 抛出异常

问题描述

我正在使用任务在后台执行繁重的任务,这样前端应用程序就不会被阻塞,同时我会随机收到“任务调度程序引发异常”错误。完整的堆栈跟踪如下

Message: "An exception was thrown by a TaskScheduler.", Data: [], InnerException: OutOfMemoryException { TargetSite: Void StartInternal(), StackTrace: "   at System.Threading.Thread.StartInternal()
   at System.Threading.Thread.Start()
   at System.Threading.Thread.Start(Object parameter)
   at System.Threading.Tasks.ThreadPoolTaskScheduler.QueueTask(Task task)
   at System.Threading.Tasks.TaskScheduler.InternalQueueTask(Task task)
   at System.Threading.Tasks.Task.ScheduleAndStart(Boolean needsProtection)", Message: "Exception of type 'System.OutOfMemoryException' was thrown.", Data: [], InnerException: null, HelpLink: null, Source: "System.Private.CoreLib", HResult: -2147024882 }, HelpLink: null, Source: "System.Private.CoreLib", HResult: -2146233088 }

下面是显示我如何使用任务的代码片段。

public async Task<bool> Method1()
{
  //Do something
  Task task = new Task(() => ProcessHeavyTaskInTheBackground(), TaskCreationOptions.LongRunning);
  task.Start(); //The above exception occurred on this line
  return true;
}

Method1() 由 API 调用

我的应用程序托管在 Azure 应用程序服务上,当我在监控部分检查指标类型“内存工作集”的指标并将聚合设置为最大值时,我可以看到最大 20-30% 的内存从我拥有的 14GB 中使用对于我的应用服务。

看到这个后,我认为问题不在于应用程序服务的 RAM,而在于任务调度程序,正如我们在异常中看到的那样。

有谁知道解决这个问题的方法是什么?提前谢谢了

标签: c#multithreadingasp.net-coreasync-await

解决方案


推荐阅读