C#如何在网页中实现异步加载

新手上路,请多包涵

代码是MSDN上的一个例子,我放在了网页中看是否能够实现,但结果并没有异步加载

后端代码

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";
        }
    }

页面代码

<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

按我的理解
同步加载的时候,Working . . . . . . .Length of the downloaded string: 这段话是同时显示在TextBox1中的

异步加载的时候,Working . . . . . . .应该先加载在TextBox2中
Length of the downloaded string:需要等到完成DownloadStringTaskAsync()方法后再加载在TextBox3中
而实际测试的结果Working . . . . . . .也需要等待DownloadStringTaskAsync()方法完成后才能加载在TextBox2中

阅读 3.7k
1 个回答

建议先了解一下 浏览器和服务器的工作简单原理,
然后是异步,这里包括浏览器的异步请求,和服务器的异步处理
Webform只是包装的结果,不要被表象迷惑

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进