0

I need to run task with current SynchronizationContext. I do it using Task factory:

                   Task.Factory.StartNew(async () =>
                    {
                       ...
                        var result =
                              await service.AsyncOperation(data);
                       ...
    
                    },
                    CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskScheduler.FromCurrentSynchronizationContext());

AsyncOperation method:

object async AsyncOperation(object data){
...
//some async operation here
await dal.SaveToDb(data);
...
}

The problem:
after executing await dal.SaveToDb(data); AsyncOperation method is not being resumed (code after dal.SaveToDb(data) is not executed at all). Seems after await it releases thread to thread pool but after async operation complete (SaveToDb) does not resume execution of remaining code.

Why is it happening ??? How can I fix it if I do really need to run task with current SynchronizationContext (because I need HttpContext there)

Ddd
  • 113
  • 2
  • 15

1 Answers1

2

How can I fix it if I do really need to run task with current SynchronizationContext (because I need HttpContext there)

If you need to run asynchronous code on the current SynchronizationContext, then just don't use TaskFactory.StartNew at all:

var result = await service.AsyncOperation(data);
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810