Task : 비동기 프로그래밍에 사용되는 클래스
System.Threading.Tasks 네임스페이스를 사용합니다.
StartNew(Action, Object, CancellationToken, TaskCreationOptions, TaskScheduler)
위 프로그램의 결과는 실행마다 순서가 달라진다. → 즉, 비동기 프로그래밍 자 그렇다면 Task만을 만드는 방법은 무엇일까? 비동기 프로그래밍이기에 Task를 시작하고 Wait를 사용하지 않으면 메인 스레드가 먼저 끝날 수도 있기에 Wait도 사용한다. 그렇다면 위 프로그램의 결과는 어떨까? 결과는 실행마다 순서가 달라진다. → 각 스레드의 완료 순서가 매번 다르기에,,, 그럼 스레드를 Task에 값을 전달하고 이를 가공한 값을 어떻게 반환할 수 있을까? Task를 사용한다. 위에서는 반환받은 값을 Result를 통해 받을 수 있었고, Wait가 없음에도 메인스레드가 먼저 끝나지 않는 이유는 Result는 Wait처럼 Task 작업이 끝날 때까지 대기하기 때문이다. https://learn.microsoft.com/ko-kr/dotnet/api/system.threading.tasks.task?view=net-8.0 https://learn.microsoft.com/ko-kr/dotnet/api/system.threading.tasks.task-1?view=net-8.0 The preceding method has the https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/ async 메서드는 await 키워드를 사용한다는 사실을 컴파일러에게 알리는데 비동기를 사용하기에 Task나 Task를 반환해야한다.(void도 가능) The https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/await 단순 비동기의 예를 들었을 때 자주 나오는 요리법이다. 아침 식사 준비에서 베이컨, 계란, 빵굽기는 동시 진행이 가능하다. 하지만 동기에서는 각 과정을 하나가 끝날 때까지 대기한다. 비동기에서는 병렬적인 처리를 통해 이를 해결할 수 있다. WhenAny Awaitable UnitySynchronizationContext https://devblogs.microsoft.com/dotnet/how-async-await-really-works/using System;
using System.Threading.Tasks
/*public System.Threading.Tasks.Task StartNew (Action<object?> action, object? state,
System.Threading.CancellationToken cancellationToken,
System.Threading.Tasks.TaskCreationOptions creationOptions,
System.Threading.Tasks.TaskScheduler scheduler);
*/
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(new Action<object>(Excute), "1");
Task.Factory.StartNew(Excute, "2");
Console.Read();
}
static void Excute(object val)
{
Console.WriteLine(val);
}
}using System;
using System.Threading.Tasks
class Program
{
static void Main(string[] args)
{
//생성자에 Excute
Task t1 = new Task(new Action(Excute));
//람다식
Task t2 = new Task(() =>
{
Console.WriteLine("1");
);
t1.Start();
t2.Start();
t1.Wait();
t2.Wait();
Console.Read();
}
static void Excute(object val)
{
Console.WriteLine("2");
}
}Task
using System;
using System.Threading.Tasks
class Program
{
static void Main(string[] args)
{
Task<float> t1 = Task.Factory.StartNew<float>(new Action<object>(Excute), "1.23");
int res = t1.Result;
Console.WriteLine(res);
Console.Read();
}
static float Excute(object val)
{
return val;
}
}
Async & Await
정의
async modifier in its signature. That signals to the compiler that this method contains an await statement; it contains asynchronous operations.
Async
public async Task<int> MyAsyncFunc()
{
await Task.Delay(1000);
return 1;
}Await
await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.
비동기 - 동기
동기

using System;
using System.Threading.Tasks;
namespace AsyncBreakfast
{
// These classes are intentionally empty for the purpose of this example. They are simply marker classes for the purpose of demonstration, contain no properties, and serve no other purpose.
internal class Bacon { }
internal class Coffee { }
internal class Egg { }
internal class Juice { }
internal class Toast { }
class Program
{
static void Main(string[] args)
{
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
Egg eggs = FryEggs(2);
Console.WriteLine("eggs are ready");
Bacon bacon = FryBacon(3);
Console.WriteLine("bacon is ready");
Toast toast = ToastBread(2);
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("toast is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
Console.WriteLine("Breakfast is ready!");
}
private static Juice PourOJ()
{
Console.WriteLine("Pouring orange juice");
return new Juice();
}
private static void ApplyJam(Toast toast) =>
Console.WriteLine("Putting jam on the toast");
private static void ApplyButter(Toast toast) =>
Console.WriteLine("Putting butter on the toast");
private static Toast ToastBread(int slices)
{
for (int slice = 0; slice < slices; slice++)
{
Console.WriteLine("Putting a slice of bread in the toaster");
}
Console.WriteLine("Start toasting...");
Task.Delay(3000).Wait();
Console.WriteLine("Remove toast from toaster");
return new Toast();
}
private static Bacon FryBacon(int slices)
{
Console.WriteLine($"putting {slices} slices of bacon in the pan");
Console.WriteLine("cooking first side of bacon...");
Task.Delay(3000).Wait();
for (int slice = 0; slice < slices; slice++)
{
Console.WriteLine("flipping a slice of bacon");
}
Console.WriteLine("cooking the second side of bacon...");
Task.Delay(3000).Wait();
Console.WriteLine("Put bacon on plate");
return new Bacon();
}
private static Egg FryEggs(int howMany)
{
Console.WriteLine("Warming the egg pan...");
Task.Delay(3000).Wait();
Console.WriteLine($"cracking {howMany} eggs");
Console.WriteLine("cooking the eggs ...");
Task.Delay(3000).Wait();
Console.WriteLine("Put eggs on plate");
return new Egg();
}
private static Coffee PourCoffee()
{
Console.WriteLine("Pouring coffee");
return new Coffee();
}
}
}비동기

Coffee cup = PourCoffee();
Console.WriteLine("Coffee is ready");
Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
Task<Toast> toastTask = ToastBreadAsync(2);
Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("Toast is ready");
Juice oj = PourOJ();
Console.WriteLine("Oj is ready");
Egg eggs = await eggsTask;
Console.WriteLine("Eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("Bacon is ready");
Console.WriteLine("Breakfast is ready!");static async Task Main(string[] args)
{
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
var eggsTask = FryEggsAsync(2);
var baconTask = FryBaconAsync(3);
var toastTask = MakeToastWithButterAndJamAsync(2);
var breakfastTasks = new List<Task> { eggsTask, baconTask, toastTask };
while (breakfastTasks.Count > 0)
{
Task finishedTask = await Task.WhenAny(breakfastTasks);
if (finishedTask == eggsTask)
{
Console.WriteLine("eggs are ready");
}
else if (finishedTask == baconTask)
{
Console.WriteLine("bacon is ready");
}
else if (finishedTask == toastTask)
{
Console.WriteLine("toast is ready");
}
await finishedTask;
breakfastTasks.Remove(finishedTask);
}
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
Console.WriteLine("Breakfast is ready!");
}
async 작업 및 await 작업의 제약 사항(추후 추가 예정)