实现异步加载html,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 AccessTheWebAsync(string url)

{

WebClient client = new WebClient();

Task getStringTask = client.DownloadStringTaskAsync(url);

DoIndependentWork();

string urlContents = await getStringTask;

return urlContents.Length;

}

void DoIndependentWork()

{

TextBox2.Text += "Working . . . . . . .\r\n";

}

}

页面代码

同步加载:

异步加载:

bV2W9Q?w=996&h=470

按我的理解

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

异步加载的时候,Working . . . . . . .应该先加载在TextBox2中

Length of the downloaded string:需要等到完成DownloadStringTaskAsync()方法后再加载在TextBox3中

而实际测试的结果Working . . . . . . .也需要等待DownloadStringTaskAsync()方法完成后才能加载在TextBox2中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值