暇之余,究多Task、async、await。

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

namespace ConsoleApp2
{
    class Program
    {

        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                Task.Run(() => Run2()); //类似于线程池,开启线程小于5
            }

            for (int i = 0; i < 5; i++)
            {
                new Thread(Run1).Start();//开启5个线程
            }

            Task<string> task = Task.Run(
                () => Thread.CurrentThread.ManagedThreadId + ""
            );
            Console.WriteLine(task.Result);//task.Result 会等到task执行完毕执行

            Console.WriteLine("-------主线程启动-------");
            Task<int> task2 = GetStrLengthAsync();
            Console.WriteLine("主线程继续执行");
            Console.WriteLine("Task返回的值" + task2.Result);
            Console.WriteLine("-------主线程结束-------");
        }

        static void Run1()
        {
            Console.WriteLine("Thread Id =" + Thread.CurrentThread.ManagedThreadId);
        }

        static void Run2()
        {
            Console.WriteLine("Task调用的Thread Id =" + Thread.CurrentThread.ManagedThreadId);
        }

        //async必须返回void Task Task<int>
        static async Task<int> GetStrLengthAsync() 
        {
            Console.WriteLine("GetStrLengthAsync方法开始执行");
            //await 必须用来修饰Task Task<TResult>,而且只能出现在async修饰的异步方法中。
            //遇到await并未开启新线程,而是遇到GetString方法中的Task.Run()时才开启了新线程
            string str = await GetString(); 
            Console.WriteLine("GetStrLengthAsync方法结束执行");
            return str.Length;
        }

        static Task<string> GetString()
        {
            Console.WriteLine("GetString方法开始执行");
            return Task.Run(() =>
            {
                Thread.Sleep(2000);
                return "GetString返回值";
            });
        }

    }


}

 

posted on 2018-01-23 09:13  chester·chen  阅读(187)  评论(0编辑  收藏  举报