async await
顺序执行
class Program
{
static void Main(string[] args)
{
new MyClass();
Console.Read();
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine(String.Format("MyClass() Start. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
DisplayValue();
Console.WriteLine(String.Format("MyClass() End. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
}
public Task<double> GetValueAsync(double num1, double num2)
{
return Task.Run(() =>
{
for (int i = 0; i < 1000000; i++)
{
num1 = num1 / num2;
}
return num1;
});
}
public void DisplayValue()
{
double result = GetValueAsync(1234.5, 1.01).Result ;
System.Threading.Thread.Sleep(5000);
Console.WriteLine(String.Format("Value is : {0} 时间:{1}",result,DateTime.Now.ToString(CultureInfo.InvariantCulture)));
}
}
异步执行
class Program
{
static void Main(string[] args)
{
new MyClass();
Console.Read();
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine(String.Format("MyClass() Start. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
DisplayValue(); //这里不会阻塞
Console.WriteLine(String.Format("MyClass() End. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
}
public Task<double> GetValueAsync(double num1, double num2)
{
return Task.Run(() =>
{
for (int i = 0; i < 1000000; i++)
{
num1 = num1 / num2;
}
return num1;
});
}
public async void DisplayValue()
{
double result = await GetValueAsync(1234.5, 1.01);//此处会开新线程处理GetValueAsync任务,然后方法马上返回
//这之后的所有代码都会被封装成委托,在GetValueAsync任务完成时调用
System.Threading.Thread.Sleep(5000);
Console.WriteLine(String.Format("Value is : {0} 时间:{1}",result,DateTime.Now.ToString(CultureInfo.InvariantCulture)));
}
}