Async & Sync 비동기 프로그래밍
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