I have the following abstract base class that all tasks inherit from.
public abstract class ScheduledTaskBase : ITask
{
private readonly ILogRecorder _logRecorder;
protected ScheduledTaskBase(ILogRecorder logRecorder)
{
_logRecorder = logRecorder;
}
protected IConfigurationRoot Configuration { get; private set; }
public void Run()
{
OnRun();
_logRecorder.LogProcessRunDate(TaskType);
}
protected abstract ScheduledTask TaskType { get; }
protected abstract void OnRun();
}
This is one of the inheriting class.
public class FailedOrderTask : ScheduledTaskBase
{
protected override ScheduledTask TaskType => ScheduledTask.FailedOrderTask;
private readonly IService _service;
public FailedOrderTask(IService service, ILogRecorder logRecorder) : base(logRecorder)
{
_service = service;
}
protected override void OnRun()
{
Task.Run(() => { _service.ProcessFailedOrders(); }).Wait();
}
}
Here is the IService's ProcessFailedOrders method.
public async Task ProcessFailedOrders()
{
var orders = await _repository.GetFailedOrders();
foreach (var order in orders)
await PlaceOrder(order);
}
And the repository's GetFailedOrders method.
public async Task<List<Order>> GetFailedOrders()
{
return await _context.Orders.Where(x => !x.DateOrdered.HasValue).ToListAsync();
}
When the task runs and gets into the repository method, it then jumps back out to the ScheduledTaskBase Run method's _logRecorder.LogProcessRunDate line. This causes a 2nd operation started on this context error. If I put a breakpoint on the _logRecorder line and then move to the next line - the closing curly brace, it then jumps back to the repository and returns the data to the service.
We have a number of other tasks that are set up the same way where they do something like the following and they work fine.
Task.Run(() => SomeClass.Method).Wait()
So I can't figure out why this one task always jumps out of the async method only to come back if I don't let the _logRecorder line execute.