C# MVC 異步操作

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.