码迷,mamicode.com
首页 > 其他好文 > 详细

异步编程学习

时间:2016-07-14 13:32:25      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

asyn修饰符只能用于返回Task或void的方法。它不能用于程序的入口点,即Main方法不能使用async修饰符。await只能用于返回.Task的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 异步
{
    class Program
    {
         static void Main(string[] args)
        {
            MethodAsync();
           // Console.WriteLine(Greeting("456"));
            Console.ReadKey();
        }
        public static string  Greeting(string name)
        {
            System.Threading.Thread.Sleep(5000);
            //Console.WriteLine("我是休眠的进程苏醒了,哈哈");
            return $"hello,我是{name}";
        }
        public static Task<string>  GreetingAsync(string name)//调用异步方法时,需要用await
        {
          return Task.Run<string>(() => { return Greeting(name); }
            );
        }
        public async static void MethodAsync()
        {
        string str = await GreetingAsync("123");
        Console.WriteLine(str);//过了5s执行该方法
        }
    }
}

 

异步编程学习

标签:

原文地址:http://www.cnblogs.com/wsn1203/p/5669998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!