Asp.net
ASP.net webforms (.NET 2.0) 中的非同步頁面處理範例
有人可以為我提供一個簡單的 ASP.NET Webforms 2.0 中的非同步頁面處理範例(我使用的是 VS 2010,所以像 lambdas 這樣的新語法是可以的)?
我有一些長時間執行的請求,我不想佔用 IIS 執行緒。
為簡單起見,假設我目前的程式碼如下所示:
protected void Page_Load(object sender, EventArgs e) { string param1 = _txtParam1.Text; string param2 = _txtParam2.Text; //This takes a long time (relative to a web request) List<MyEntity> entities = _myRepository.GetEntities(param1, param2); //Conceptually, I would like IIS to bring up a new thread here so that I can //display the data after it has come back. DoStuffWithEntities(entities); }如何修改此程式碼以使其非同步?假設我已經在 aspx 頁面中設置了 async=“true”。
編輯
我想我知道如何得到我想要的東西。我已將範常式式碼放在此處的答案中。隨時指出可以進行的任何缺陷或更改。
我問過 ASP.NET 團隊的一些人。這是他們給我的電子郵件回复,現在,給你。
所有這些程式碼最終都會啟動一個新執行緒並在該執行緒上執行委託呼叫。所以現在有兩個執行緒在執行:請求執行緒和新執行緒。因此,該範例的性能實際上比原始同步程式碼的性能要差。
有關如何在 ASP.NET 中編寫和使用非同步方法的範例,請參閱http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45 。
這是一個簡單的非同步處理範例。
protected void Page_Load(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); ThreadPool.QueueUserWorkItem(state => Dokimes_Programming_multithread_QueryWorkThead.ThreadProc2()); Debug.Write("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the thread pool task runs. The thread pool uses background // threads, which do not keep the application running. (This // is a simple example of a race condition.) // Thread.Sleep(4000); txtDebug.Text += "ended"; Debug.Write("end."); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, so stateInfo is null. Debug.Write(" Hello from the thread pool 1."); } static void ThreadProc2() { // No state object was passed to QueueUserWorkItem, so stateInfo is null. Debug.Write("Hello from the thread pool 2."); }另一種方式
您可以使用 PageAsyncTask,請參閱此處的完整範例:http:
//msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx
就像是
clAsynCustomObject oAsynRun = new clAsynCustomObject(); PageAsyncTask asyncTask = new PageAsyncTask(oAsynRun.OnBegin, oAsynRun.OnEnd, oAsynRun.OnTimeout, null, true); Page.RegisterAsyncTask(asyncTask); Page.ExecuteRegisteredAsyncTasks();