Reputation: 73
public ActionResult AsyncAction()
{
Task task = new Task(httpContext => {
System.Web.HttpContext.Current = httpContext as HttpContext;
Thread.Sleep(1000 * 10);
var x = System.Web.HttpContext.Current.Request.Form["x"];
//To do...Contains IO/NET Write/Read Operation...
}, System.Web.HttpContext.Current);
task.Start();
return View();
}
MSDN say:
Any public static members of System.Web.HttpContext are thread safe.
In my codes is thread safe?
Upvotes: 0
Views: 1687
Reputation: 171178
It is not thread-safe because you are using the same HttpContext
concurrently on multiple threads. The docs don't state that this is safe.
Upvotes: 1
Reputation: 6505
Your code is thread-safe but it is strangely written. Why not write it as:
Task task = new Task(httpContext => {
Thread.Sleep(1000 * 10);
var x = httpContext.Request.Form["x"];
//To do...Contains IO/NET Write/Read Operation...
}, System.Web.HttpContext.Current);
In general I prefer to use Current
as little as possible and instead pass around the context explicitly. That way your code will work even if it's invoked asynchronously.
Unless your question is specifically about assigning to the Current
property and having it not be changed by another thread while yours is asleep? That certainly seems like a safe thing to do, but I can find no documentation to support it and looking at System.Web
in Reflector it's not obviously impossible (e.g. it's not marked as TheadLocal
). To be on the safe side, I would rewrite as above.
Upvotes: 0