2012-02-20 33 views
0

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この行を使用している理由は何ですか –

答えて

1

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

あなたはコードがあなたの要求はまだ同期的に処理され、完了するために非同期子孫を待っていないので、失敗にバインドされています。名前が示すとおり、HttpRequest.Currentは現在の要求に関連付けられています。しかし、ステートメントを返すView();あなたは基本的にasp.netにそのことを行い、できるだけ早くリクエストを終了するように指示し、リクエストが終了/終了/終了してからHttpRequest.Currentを無効にします。

非同期タスクが完了するのを待つか、非同期タスクのHttpContext.Currentに依存しないでください。

関連する問題