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
. β BidetTask.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 tasks β Wrungvar t = new Thread(...)
) are not taken from the thread pool, so they will not interfere with request handling. β BidetTask.Run
will take away a thread from the requestpool, since it's run with the current context's scheduler, which is ASP.NET Core's scheduler. Most important argument though is, you have no guarantees it will ever complete (i.e. IIS could shut down your ASP.NET Core process and with it your background tasks at any time for any reason) β WrungThread.StartNew
spawns a completely new thread which does not come from the thread pool, so your previous comment is beside the point. β Bidet