c#异步之Task
public class TestTask { private string Uname = "joyet"; private int Num1 = 109; private int Num2 = 5; private int Num3 = 0; //task->async异步方法和await,主线程碰到await时会立即返回,继续以非阻塞形式执行主线程下面的逻辑 /// <summary> /// 测试Task添加异步方法 /// </summary> public async void TestAsyncShow() { Console.WriteLine("异步Show方法开始====="); await Task.Run(() => { TestMethods.Show(Uname); }); Console.WriteLine("异步Show方法结束=====。"); } /// <summary> /// 测试Task添加异步方法 /// </summary> public async void TestAsyncPlus() { Console.WriteLine("异步Add方法开始====="); //Task异步调用方法获取返回值方法1 int result1 = await TestAsyncPlusCallBack(); Console.WriteLine("异步Add方法相加结果1:" + Convert.ToString(result1)); //Task异步调用方法获取返回值方法1 var result2 =await Task.Run(() => { return TestMethods.Add(Num1, Num2); }); Console.WriteLine("异步Add方法相加结果2:" + Convert.ToString(result2)); Console.WriteLine("异步Add方法结束=====。"); } /// <summary> /// 测试Task添加异步处理及返回参数方法 /// </summary> /// <param name="result"></param> private async Task<int> TestAsyncPlusCallBack() { int result = 0; await Task.Run(() => { result = TestMethods.Add(Num1, Num2); }); return result; } }