ConfigureAwait(false) in long running task

183 views Asked by At

I May have a misconception about something. For me in an async method, having ConfigureAwait(false); will permit the task to continue being executed on the threadpool.

So if I Declare a LongRunning Task on a dedicated thread, for a background work (like checking some work on a queue)

   _managementTask = Task.Factory.StartNew(async () =>
   {
    while (!_cancellationToken.IsCancellationRequested)
    {
       await Task.Delay(10000, _cancellationToken).ConfigureAwait(false);
       await CheckWork().ConfigureAwait(false);
    }
   }, TaskCreationOptions.LongRunning);

Then it means that because of the first ConfigureAwait(false), all the following code and loops will be excuted on the threadpool instead of on a the dedicated thread created by the "LongRunning" Task Creation, so It would be the same as executing a task on the threadpool from the very start.

Please correct me if i'm wrong.

1

There are 1 answers

16
Stephen Cleary On

That is correct, which is why LongRunning is almost always useless with an async delegate.

Furthermore, if there's no current task scheduler (and there usually isn't one), then the same is true for any await, with or without ConfigureAwait(false).

As a side note, LongRunning is just a hint to the thread pool. It doesn't guarantee a dedicated thread.

As a general rule, use Task.Run to schedule asynchronous work to the thread pool, not Task.Factory.StartNew.