C#异步处理操作错误

时间:2012-02-20 06:13:34

标签: asp.net-mvc-3 asynchronous

基于的WEB应用程序。 NET MVC 3建立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 ();
            }

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

您的代码必然会失败,因为您的请求仍然是同步处理的,并且不会等待异步后代完成。顾名思义,HttpRequest.Current与当前请求相关联。然后用语句返回View();你基本上告诉asp.net做它的东西并尽快结束请求,从而使HttpRequest.Current无效,因为请求已经结束/结束/关闭。

您必须等待异步任务完成或不依赖异步任务中的HttpContext.Current。