C# MVC 異步操作

1.建立HomeController類,繼承AsyncController

代碼如下:

View Code
  public class HomeController : AsyncController
{
public void IndexAsync()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
AsyncManager.OutstandingOperations.Increment();
var task = Task.Factory.StartNew(() => DoStuff("Some other stuff"));
task.ContinueWith(t =>
{
AsyncManager.Parameters["model"] = t.Result;
ViewBag.message = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});

}
private string DoStuff(string input)
{
Thread.Sleep(5000);
return input;
}
public ActionResult IndexCompleted(string model)
{
return View();
}

}

2.定義異步的方法 IndexAsync,也是acton,需要注意的是。該方法必須是返回值是void

前面是方法名Index+Asnc,必須加Asnc。

在這個方法中,加入一個線程調用的方法。在本例子中是

    var task = Task.Factory.StartNew(() => DoStuff("Some other stuff"));
            task.ContinueWith(t =>
            {
                AsyncManager.Parameters["model"] = t.Result;
                ViewBag.message = t.Result;
                AsyncManager.OutstandingOperations.Decrement();
            });

3.異步開始

AsyncManager.OutstandingOperations.Increment();

4.線程結束

AsyncManager.OutstandingOperations.Decrement();

5.傳遞變量

AsyncManager.Parameters["model"] = t.Result;

其中,model是要傳遞的變量名稱,在完成異步中調用

同樣,也可以用collection中的數據保存方法,也可以傳遞變量,如:ViewBag.message = t.Result;

6.完成異步,返回數據IndexCompleted

包括名稱Index+Completed

如這個方法  

  public ActionResult IndexCompleted(string model)
        {
            return View();
        }

這裡的model參數,就是AsyncManager.Parameters["model"] = t.Result;傳遞過來的數值。

如果AsyncManager.Parameters中定義幾個變量,那麼在這個方法的參數中加上,就傳遞過來了。

同樣collection中數據是共享的。

7.調用這個collection方式是

Home/Index

原文地址:https://www.cnblogs.com/cxd4321/p/2400702.html