Task async/await

来源:互联网 发布:网络聊天软件 编辑:程序博客网 时间:2024/06/08 17:13


1、只有async没有await 会报警告,并当做普通方法执行
2、await后面的内容会被当做是该Task的回调进行执行
3、 返回的结果是Task<T>,其中T为最终结果
4、await关键字只能放在Task前面

5、如果没有return 默认返回Task


返回 Task

 static void Main(string[] args)        {            try            {                Console.WriteLine("***************程序开始 线程ID:{0}*******************",Thread.CurrentThread.ManagedThreadId);                TaskFactory taskfactory = new TaskFactory();                taskfactory.StartNew(new Action(() => {                    Console.WriteLine("调用DoAsync前");                    DoAsync();                    Console.WriteLine("调用后前");                }));                Console.WriteLine("***************程序结束 线程ID:{0}*******************", Thread.CurrentThread.ManagedThreadId);                Console.Read();            }            catch (Exception ex)            {                throw;            }        }        /// <summary>        /// async await 会默认返回Task 不需要return        /// 如果需要返回一个类型 如 string 返回值部分需要写 Task<string>        /// </summary>        /// <returns></returns>        public static async Task<string> DoAsync()        {            Task task = Task.Run(new Action(() => {                Console.WriteLine("执行了一个Task Run");            }));            await task;//跳出方法 下面的将作为回调函数执行            Thread.Sleep(1000);//休眠1秒            Console.WriteLine("DoAsync 执行完毕 当前线程ID为{0}", Thread.CurrentThread.ManagedThreadId);            return "123";        }
结果



非Task返回值

static void Main(string[] args)        {            try            {                Console.WriteLine("***************程序开始 线程ID:{0}*******************",Thread.CurrentThread.ManagedThreadId);                TaskFactory taskfactory = new TaskFactory();                taskfactory.StartNew(new Action(() => {                    Console.WriteLine("调用DoAsync前");                    Task<string> t= DoAsync();                    Console.WriteLine("调用DoAsync后 返回值为{0}",t.Result);                }));                Console.WriteLine("***************程序结束 线程ID:{0}*******************", Thread.CurrentThread.ManagedThreadId);                Console.Read();            }            catch (Exception ex)            {                throw;            }        }        /// <summary>        /// async await 会默认返回Task 不需要return        /// 如果需要返回一个类型 如 string 返回值部分需要写 Task<string>        /// </summary>        /// <returns></returns>        public static async Task<string> DoAsync()        {            Task task = Task.Run(new Action(() => {                Console.WriteLine("执行了一个Task Run");            }));            await task;//跳出方法 下面的将作为回调函数执行            Thread.Sleep(1000);//休眠1秒            Console.WriteLine("DoAsync 执行完毕 当前线程ID为{0}", Thread.CurrentThread.ManagedThreadId);            return "123";        }


结果




0 0
原创粉丝点击