C#异步处理操作错误

C#异步处理操作错误

问题描述:

基于WEB应用程序。 NET MVC 3,建立C#异步工作价值的错误,代码如下:C#异步处理操作错误

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(); 
      } 
+0

System.Web.HttpContext.Current为什么要使用此行,您准确地要什么 – 2012-02-20 06:30:11

由于HttpContext绑定到当前请求,一旦你返回它将不再可用。但是你的异步任务继续在后台运行,当它试图访问它时,它不再可用。因此,您应该将所有依赖关系作为参数传递给该任务:

public ActionResult Contact() 
{ 
    // everything that depends on an HttpContext should be done here and passed 
    // as argument to the task 
    string p = HttpContext.Server.MapPath("~/test.txt"); 

    // Create an asynchronous processing operations 
    Task task = new Task(state => 
    { 
     var path = (string)state; 
     var testTexts = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; 
     foreach (string text in testTexts) 
     { 
      System.IO.File.AppendAllText(path, text); 

      // Thread to hang five seconds to simulate asynchronous time difference 
      Thread.Sleep(5000); 
     } 
    }, p); 

    // Asynchronous processing 
    task.Start(); 
    return View(); 
} 

你的代码是注定要失败,因为您的请求仍然是同步处理,不等待异步后代来完成。顾名思义,HttpRequest.Current与当前请求相关联。然而声明返回View();你基本上告诉asp.net尽其所能,尽快结束请求,从而导致HttpRequest.Current无效,因为请求已被结束/结束/关闭。

您必须等待异步任务完成或不要依赖HttpContext.Current才能完成异步任务。