如果想學習asp.net2.0的異步頁技術,那么一定要仔細閱讀http://www.microsoft.com/china/msdn/library/default.mspx?mfr=true,并且下載它的源代碼仔細揣摩。全文共介紹了3種實現異步頁的編程模型,且功能一種比一種強大。多余的我就不多說了,直接看最后一種模型:使用pageasynctask類、registerasynctask方法、executeregisteredasynctasks方法和timeoutasyncoperation方法注冊并執行異步任務,并針對長時間無響應的情況調用超時處理方法。原文所提供源碼的asyncpagetask.aspx.cs文件詳細示例了使用這個模型實現異步頁的方法。
        這個模型最大的好處在于可以在一次頁面請求中處理多個異步任務,并且還可以用超時處理來避免在執行異步操作時出現的無響應情況。原作者僅僅在page_load中注冊了一個異步任務,那么我們仿照他的做法,再注冊一個異步任務,如下所示:
<%@ page async="true" asynctimeout="5" language="c#" masterpagefile="~/site.master" autoeventwireup="true" codefile="asyncpagetask.aspx.cs" inherits="asyncpagetask" title="untitled page" %>
protected void page_load(object sender, eventargs e)
    {
        if (!ispostback)
        {
            pageasynctask task = new pageasynctask(
                new begineventhandler(beginasyncoperation),
                new endeventhandler(endasyncoperation),
                new endeventhandler(timeoutasyncoperation),
                null
            );
            pageasynctask task1 = new pageasynctask(
                new begineventhandler(beginasyncoperation1),
                new endeventhandler(endasyncoperation1),
                new endeventhandler(timeoutasyncoperation1),
                null
            );
            registerasynctask(task);
            registerasynctask(task1);
        }
    }
        如果在頁面屬性asynctimeout的規定時間內得到異步任務返回的結果,那么頁面將按照我們預期的顯示。但是如果在執行第一個任務時遇到了小麻煩,耽誤了時間會怎么樣呢?有兩種可能:一是,第一個任務的結果最終返回并顯示出來,而第二個任務剛一啟動就被判定為超時,從而執行了它的timeoutasyncoperation方法;二是,第一個任務沒有等到返回結果就已被判超時,因此第二個任務也一定被判超時了。以上情況是由于兩個異步任務分享了asynctimeout規定的時間,只要前面那個任務在執行時耽誤了時間,必然影響到后面那個任務的運行。那么能不能讓兩個異步任務獨享asynctimeout規定的時間呢,這就要在executeregisteredasynctasks方法上找出路了。
        值得注意的是,每次調用executeregisteredasynctasks時,asp.net2.0都將重置asynctimeout屬性,這意味著有可能實現異步任務獨享asynctimeout規定的時間。按照目前程序的寫法,如果不顯示調用executeregisteredasynctasks方法,asp.net2.0會在頁面生命周期中的prerendercomplete
事件之前自動調用executeregisteredasynctasks方法來運行這兩個注冊的異步任務。因為只執行了一次executeregisteredasynctasks卻運行了兩個任務,那么這兩個任務便只好分享asynctimeout規定的運行時間了。于是我對代碼做了如下調整:
protected void page_load(object sender, eventargs e)
    {
        if (!ispostback)
        {
            pageasynctask task = new pageasynctask(
                new begineventhandler(beginasyncoperation),
                new endeventhandler(endasyncoperation),
                new endeventhandler(timeoutasyncoperation),
                null
            );
            pageasynctask task1 = new pageasynctask(
                new begineventhandler(beginasyncoperation1),
                new endeventhandler(endasyncoperation1),
                new endeventhandler(timeoutasyncoperation1),
                null
            );
            registerasynctask(task);
            executeregisteredasynctasks();
            registerasynctask(task1);
            executeregisteredasynctasks();
        }
    }
        乍一看似乎有點問題:第二個executeregisteredasynctasks方法會不會將注冊的第一個異步任務又執行一次?其實不會的,因為asp.net2.0已經規定同一個異步方法只會執行一次。因此這樣就使兩個異步任務獨享了運行時間,避免了互相干擾。
新聞熱點
疑難解答
圖片精選