Reputation: 328
I have an async method, which uses HttpContext.Current, which is used by another code, which is running in background, like
var result = Task.Run(async () => await SomeMethod()).Result;
HttpContext.Current is always null though. Is there a way to pass HttpContext into background task?
Upvotes: 2
Views: 2023
Reputation: 456322
Is there a way to pass HttpContext into background task?
Technically yes, you can set HttpContext.Current
. However, you really don't want to do this. HttpContext
is intended for use by only one thread at a time.
A better solution is to remove the Task.Run
entirely:
await SomeMethod();
Task.Run
shouldn't be used on ASP.NET in the first place.
It looks like the code may be trying to use Task.Run
to do a "fire and forget", in which case Task.Run
is a very dangerous and incomplete "solution". The proper solution for fire-and-forget is asynchronous messaging, i.e., a durable queue with a separate background service.
Upvotes: 7