代码是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";
}
}
页面代码
同步加载:
异步加载:
按我的理解
同步加载的时候,Working . . . . . . .Length of the downloaded string: 这段话是同时显示在TextBox1中的
异步加载的时候,Working . . . . . . .应该先加载在TextBox2中
Length of the downloaded string:需要等到完成DownloadStringTaskAsync()方法后再加载在TextBox3中
而实际测试的结果Working . . . . . . .也需要等待DownloadStringTaskAsync()方法完成后才能加载在TextBox2中