I am using Tasks to perform the heavy tasks in the background so that the front-end application won't be blocked, while doing so I get this "An exception was thrown by a TaskScheduler" error randomly. The complete stack trace is as followed
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 }
Below is the code snippet which shows How I use the tasks.
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() is called by the API
My application is hosted on Azure app service, when I checked the Metrics in the monitoring section for the metric type "Memory working set" and Aggregation is set to max, I could see max 20-30% memory was utilized from 14GB which I have for my app service.
After seeing this I thought the problem is not with the RAM of the app service it is with the task scheduler as we can see in the exception.
Has anybody known what is the fix for this? Many thanks in advance