WEB applications based on. NET MVC 3 to establish the C # asynchronous operating value error, code as follows:
public ActionResult Contact ()
{
/ / Create an asynchronous processing operations
Task task = new Task (() => {
string [] testTexts = new string [10] {"a", "b", "c", "d", "e", "f", "g", "h" , "i", "j"};
foreach (string text in testTexts)
{
/ / The following line does not have a problem
System.IO.File.AppendAllText (Server.MapPath ("/ test.txt"), text);
/ / The following line to be a problem, find a solution. Because some other program of practical application in my project set to use System.Web.HttpContext.Current
/ / System.IO.File.AppendAllText (System.Web.HttpContext.Current.Server.MapPath ("/ test.txt"), text);
/ / Thread to hang five seconds to simulate asynchronous time difference
System.Threading.Thread.Sleep (5000);
}
});
/ / Asynchronous processing
task.Start ();
return View ();
}
Since the HttpContext is bound to the current request, once you return it will no longer be available. But your asynchronous task continues to run in the background and when it attempts to access it, it is no longer available. For this reason you should pass all dependencies to the task as a parameter: