본문 바로가기
C#/C# Common

Async & Sync 비동기 프로그래밍

by doublerabbits 2022. 6. 22.

Async & Sync 비동기 프로그래밍

 

AsyncAwait.zip
0.01MB

 

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncAwait
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // case 1
            //label1.Text = BigLongImportantMethod("John");

            // case 2 : Task
            //Task.Factory.StartNew(() => BigLongImportantMethod("Sally")).ContinueWith(t => label1.Text = t.Result, TaskScheduler.FromCurrentSynchronizationContext());

            // case 3 : async & await
            Console.WriteLine($"step 0 : Async & Await");
            CallBigImportantMethod();
            Console.WriteLine($"step 5 : Waiting...");
            label1.Text = "Waiting...";
        }

        private async void CallBigImportantMethod()
        {
            Console.WriteLine($"step 1 : CallBigImportantMethod start");
            Console.WriteLine($"step 2 : await meet");
            var result = await BigLongImportantMethodAsync("Andrew");
            Console.WriteLine($"step 8 : await bye");
            label1.Text = result;
            Console.WriteLine($"step 9 : CallBigImportantMethod end");
        }

        private Task<string> BigLongImportantMethodAsync(string name)
        {
            Console.WriteLine($"step 3 : BigLongImportantMethodAsync start");
            Task<string> T = Task.Factory.StartNew(() => BigLongImportantMethod(name));
            Console.WriteLine($"step 4 : BigLongImportantMethodAsync end");
            return T;
        }

        private string BigLongImportantMethod(string name)
        {
            Console.WriteLine($"step 6 : Long time job start");
            Thread.Sleep(2000);
            Console.WriteLine($"step 7 : Long time job end");
            return "Hello, " + name;
        }
    }
}

 

 

 

 

 

 

 

https://www.youtube.com/watch?v=DqjIQiZ_ql4 

 

 

'C# > C# Common' 카테고리의 다른 글

LINQ  (0) 2022.09.01
Event  (0) 2022.08.30
Anonymous Methods and Lambda Expression  (0) 2022.08.30
Generic  (0) 2022.08.16
가변 인수  (0) 2022.06.30