In ASP.NET Core, I am using IHttpContextAccessor
to access the current HttpContext
. HttpContextAccessor
uses AsyncLocal<T>
.
In one situation, I am trying to start a Task
from within a request, that should continue running after the request has ended (long running, background task), and I am trying to detach it from the current execution context so that IHttpContextAccessor
returns null
(otherwise I am accessing an invalid HttpContext
).
I tried Task.Run
, Thread.Start
, but every time, the context seems to carry over and IHttpContextAccessor
returns the old context whatever I try (sometimes even contexts from other requests 🤔).
How can I start a task that will have a clean AsyncLocal
state so that IHttpContextAccessor
returns null
?
HttpContext
.Task.Run(...)
, etc. has a parameter where you can set the scheduler. You could set the default scheduler in here (ASP.NET Core runs its own scheduler), i.e.Task.Run(() => DoSomething(), TaskScheduler.Default)
. But again, I do not recommend you doing that and you should consider a real background process like described above, because threads taken away for background tasks are threads which can't be used to accept request. ASP.NET Core should just useawait
/async
for true async operation, not CPU intensive stuff or background tasksThread.StartNew
spawns a completely new thread which does not come from the thread pool, so your previous comment is beside the point.