Running a task with a pure AsyncLocal state

In ASP.NET core I use IHttpContextAccessor

to access the current HttpContext

. HttpContextAccessor

usesAsyncLocal<T>

.

In one situation I am trying to start Task

from a request that needs to continue running after the request completes (long running, background task) and I am trying to decouple it from the current execution context so that it IHttpContextAccessor

returns null

(otherwise I am accessing an invalid one HttpContext

).

I tried Task.Run

, Thread.Start

but every time the context seems to be carried over and it IHttpContextAccessor

returns the old context no matter what I try (sometimes even contexts from other requests 🤔).

How do I start a task with a clean state AsyncLocal

to IHttpContextAccessor

return null

?

+3


source to share


1 answer


You can wait for a long job and set it HttpContext

to null inside the wait . This is safe for all code outside the task.

[Fact]
public async Task AsyncLocalTest()
{
    _accessor = new HttpContextAccessor();

    _accessor.HttpContext = new DefaultHttpContext();

    await LongRunningTaskAsync();

    Assert.True(_accessor.HttpContext != null);
}

private async Task LongRunningTaskAsync()
{
    _accessor.HttpContext = null;
}

      

You can start a separate thread, it doesn't matter.



Task.Run(async () => await LongRunningTaskAsync());

      

Just make a task pending cleanup HttpContext

just for the task's async context.

+1


source







All Articles