鍍金池/ 問(wèn)答/C#/ C#如何在網(wǎng)頁(yè)中實(shí)現(xiàn)異步加載

C#如何在網(wǎng)頁(yè)中實(shí)現(xiàn)異步加載

代碼是MSDN上的一個(gè)例子,我放在了網(wǎng)頁(yè)中看是否能夠?qū)崿F(xiàn),但結(jié)果并沒(méi)有異步加載

后端代碼

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //同步加載
            WebClient client = new WebClient();
            string getstringtask = client.DownloadString("http://msdn.microsoft.com");
            TextBox1.Text += "Working . . . . . . .\r\n";
            TextBox1.Text += String.Format("\r\nLength of the downloaded string: {0}.\r\n", getstringtask.Count());

        }

        protected async void Button2_Click(object sender, EventArgs e)
        {
            //異步加載
            int contentLength = await AccessTheWebAsync("http://msdn.microsoft.com");
            TextBox3.Text += String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);

        }

        async Task<int> AccessTheWebAsync(string url)
        {
            WebClient client = new WebClient();
            Task<string> getStringTask = client.DownloadStringTaskAsync(url);

            DoIndependentWork();

            string urlContents = await getStringTask;
            return urlContents.Length;
        }

        void DoIndependentWork()
        {
            TextBox2.Text += "Working . . . . . . .\r\n";
        }
    }

頁(yè)面代碼

<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        同步加載:<asp:TextBox ID="TextBox1" runat="server" Height="179px" Width="379px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="同步加載" />
        <br />
        異步加載:<asp:TextBox ID="TextBox2" runat="server" Height="222px" Width="374px" AutoPostBack="true"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server" Height="222px" Width="374px" AutoPostBack="true"></asp:TextBox>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="異步加載" />
    </form>
</body>

clipboard.png

按我的理解
同步加載的時(shí)候,Working . . . . . . .Length of the downloaded string: 這段話是同時(shí)顯示在TextBox1中的

異步加載的時(shí)候,Working . . . . . . .應(yīng)該先加載在TextBox2中
Length of the downloaded string:需要等到完成DownloadStringTaskAsync()方法后再加載在TextBox3中
而實(shí)際測(cè)試的結(jié)果Working . . . . . . .也需要等待DownloadStringTaskAsync()方法完成后才能加載在TextBox2中

回答
編輯回答
冷眸

建議先了解一下 瀏覽器和服務(wù)器的工作簡(jiǎn)單原理,
然后是異步,這里包括瀏覽器的異步請(qǐng)求,和服務(wù)器的異步處理
Webform只是包裝的結(jié)果,不要被表象迷惑

2018年9月11日 02:06