1、 页面头部 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Async="true" %>
2、
protected async void Button1_Click(object sender, EventArgs e)
{
//TextBox1.Text = new Class1().Start();
int contentLength = await AccessTheWebAsync(); //这里会阻塞后面的执行
TextBox1.Text += "1245";
TextBox1.Text += contentLength;
}
async Task<int> AccessTheWebAsync() // 这里的返回值类型 Task<T> void Task
{
HttpClient client = new HttpClient();
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
DoIndependentWork();
string urlContent = await getStringTask;
return urlContent.Length;
}
void DoIndependentWork()
{
TextBox1.Text += "Working.......";
}
第二种方式:
public string Start()
{
Diaplay(); //这里不会阻止线程执行
return result.ToString() + "12454";
}
public async void Diaplay()
{
double result = await GetValueAsync(124.12, 1.122);
}
Task<double> GetValueAsync(double num1, double num2)
{
return Task.Run(() =>
{
for (int i = 0; i < 10000; i++)
{
num1 = num1 / num2;
}
return num1;
});
}