C\#의 비동기 프로 그래 밍:await 와 async

코드 예제 에 따라 학습 합 니 다.
  • 시간 소 모 를 모 의 하 는 함 수 를 만 듭 니 다.여 기 는GetSomeThing함수 입 니 다.
  • 비동기 프로 그래 밍 을 사용 하려 면 async 수식 방법 으로 호출GetSomeThing함 수 를 포장 해 야 합 니 다.이 함수 의 반환 값 은 Task 형식 입 니 다.이 유형 은 병렬 연산 을 하 는 작업 참조 입 니 다.이 예제ConsumeManyTime함수 입 니 다.
  • 지금 은 비동기 방식 을 직접 사용 할 수 있 습 니 다.TestOne()함수 중의 코드 를 참고 하 세 요.사실은 두 번 째 단계 의 함수ConsumeManyTime()를 직접 호출 하 는 것 입 니 다.

  • 요약:비동기 프로 그래 밍 은 예제 3 단계 이지 만 사실은 두 단계 의 일이 다.첫 번 째 단 계 는 아 날로 그 응용 이 고 비동기 프로 그래 밍 자체 와 관계 가 없다.두 번 째 단 계 는 Task 반환 유형async의 수식 방법 을 포장 하고 이 방법 은 실제 응용 함 수 를 호출 하 며 세 번 째 단 계 는 두 번 째 단계 의 방법 을 호출 하여 아 날로 그 응용 에 대한 비동기 집행 을 실시한다.
    추가:비동기 프로 그래 밍 을 제외 하고 C\#는 동시 프로 그래 밍 과 관련 된 기능 을 제공 하여 동시 작업 의 개발 을 크게 간소화 하여 개발 자 들 이 스 레 드 탱크 를 만 들 거나 스 레 드 를 관리 하지 않 아 도 동시 개발 이 가 져 온 장점 을 직접 사용 할 수 있 습 니 다.예시 코드 참조Testpallral().
    코드 는 다음 과 같다.
    class Program
        {
    
            static int i = 0;
            //         IO
            public static bool GetSomeThing(string a)
            {
                Thread.Sleep((new Random()).Next()%10*1000);
                i++;
                Console.WriteLine(DateTime.Now.ToLongTimeString()+"5-" + Thread.GetCurrentProcessorId().ToString());
                return true;
            }
            //    task  ,      GetSomeThing
            public static Task GetSomeThingAsync(string a)
            {
                return Task.Run(()=> { return GetSomeThing(a); }
                );
            }
    
        //  1:           ,  async  ,     await。       await     ,           , await                  ,
        public async static void ConsumeManyTime()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "3-" +Thread.GetCurrentProcessorId().ToString());
            bool result = await GetSomeThingAsync("test");
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "4-" +Thread.GetCurrentProcessorId().ToString());
        }
        //  2:               ,             ,           。
        public static void ContinueTaskWithConsumeManyTime()
        {
            Task t1 = GetSomeThingAsync("test");
            t1.ContinueWith(t => { Console.WriteLine("after await finished " + t.Result + " " + Thread.GetCurrentProcessorId().ToString() + " " + i.ToString()); });
        }
        //  3:       
        public static async void TaskWhenConsumeManyTime()
        {
            Task t1 = GetSomeThingAsync("test");
            Task t2 = GetSomeThingAsync("test");
            await Task.WhenAll(t1, t2);
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "6-" + Thread.GetCurrentProcessorId().ToString());
    
        }
    
        //async  await     
        public static void TestOne()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
            ConsumeManyTime();
            ConsumeManyTime();
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
            Console.WriteLine("    ");
            while (Console.ReadLine() != "stop")
            {
                Console.WriteLine("    ");
            }
        }
    
        public static void TestWithContinue()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
            ContinueTaskWithConsumeManyTime();
            ContinueTaskWithConsumeManyTime();
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
            Console.WriteLine("    ");
            while (Console.ReadLine() != "stop")
            {
                Console.WriteLine("    ");
            }
        }
    
        public static void TestWhen()
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
            TaskWhenConsumeManyTime();
    
            Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
            Console.WriteLine("    ");
            while (Console.ReadLine() != "stop")
            {
                Console.WriteLine("    ");
            }
        }
    
        public static  void Testpallral()
        {
            ParallelLoopResult result =
    
                  Parallel.For(0, 100, async (int i) =>
    
                  {
    
                      Console.WriteLine(DateTime.Now.ToLongTimeString() + "{0}, task: {1}, thread: {2}", i,
    
                      Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
    
                      await Task.Delay(10);
                      Console.WriteLine(DateTime.Now.ToLongTimeString() + "after delay");
    
                  });
    
            while (Console.ReadLine() != "stop")
            {
                Console.WriteLine("    ");
            }
        }
    
        public static void Testpallral2()
        {
            ParallelLoopResult result =
                  Parallel.For(0, 100,async(int i, ParallelLoopState pls) =>
                  {
                      Console.WriteLine(DateTime.Now.ToLongTimeString() + "{0}, task: {1}, thread: {2}", i,
                      Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
    
                      await Task.Delay(10);
                        if (i > 5) pls.Break();
                Console.WriteLine(DateTime.Now.ToLongTimeString() + "after delay");
    
                  }
            );
    
            while (Console.ReadLine() != "stop")
            {
                Console.WriteLine("    ");
            }
        }
        static void Main(string[] args)
        {
            //TestWhen();
            //Testpallral2();
    
        }
    
    }

    좋은 웹페이지 즐겨찾기