logo MSJO.kr

Concurrency in C# Example

2021-12-08
MsJ
 

C#, .NET 프로그램에 사용할 수 있는 라이브러리 및 언어 기능을 사용하면 동시성(Concurrency) 구현을 쉽게 할 수 있다. 이전 강좌에서 C++ 예제로 Concurrent computing에 대한 개념1을 설명했다. 추가로 동시성 개요2를 다시 정리해 보면 다음과 같다.

  • Concurrency : Doing more than one thing at a time. (MSJO.kr, Concurrency Example)
  • Multithreading : A form of concurrency that uses multiple threads of execution.
  • Parallel Processing : Doing lots of work by dividing it up among multiple threads that run concurrently.
  • Asynchronous Programming : A form of concurrency that uses futures or callbacks to avoid unnecessary threads. (MSJO.kr, Async-Await-Task Example)
  • Reactive Programming : A declarative style of programming where the application reacts to events.

여기에 사용한 예제3는 gavilanch3(Youtube) - Introduction to Concurrency in C#, 강좌를 참고하였다.

일반 비동기 방식
using System.Diagnostics;

var stopWatch = new Stopwatch();
var names = new List<string>() { "홍길동", "홍길서", "홍길남", "홍길북" };

Console.WriteLine("Default Start...(8초)");
stopWatch.Start();
foreach (var name in names)
{
    await Method1(name);
    await Method2(name);
    await Method3(name);
    await Method4(name);
}
stopWatch.Stop();
WriteTime(stopWatch.Elapsed.Seconds, ConsoleColor.Red);
Concurrency 방식
Console.WriteLine("Concurrency Start...(2초)");
stopWatch.Restart();
var validations = names.Select(name => MethodValidation(name));
await Task.WhenAll(validations);
stopWatch.Stop();
WriteTime(stopWatch.Elapsed.Seconds, ConsoleColor.Red);
Parallel 방식
Console.WriteLine("Parallel Start...(2초)");
stopWatch.Restart();
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 4 };
await Parallel.ForEachAsync(names, parallelOptions, async (name, token) =>
{
    await MethodValidation(name);
});
stopWatch.Stop();
WriteTime(stopWatch.Elapsed.Seconds, ConsoleColor.Red);
공통 소스
static async Task MethodValidation(string name)
{
    await Method1(name);
    await Method2(name);
    await Method3(name);
    await Method4(name);
}

static async Task Method1(string name)
{
    await Task.Delay(500);
    Console.WriteLine("Method1 : " + name);
}

static async Task Method2(string name)
{
    await Task.Delay(500);
    Console.WriteLine("Method2 : " + name);
}

static async Task Method3(string name)
{
    await Task.Delay(500);
    Console.WriteLine("Method3 : " + name);
}

static async Task Method4(string name)
{
    await Task.Delay(500);
    Console.WriteLine("Method4 : " + name);
}

static void WriteTime(int seconds, ConsoleColor color)
{
    Console.ForegroundColor = color;
    Console.WriteLine("소요시간 : " + seconds.ToString() + "\r\n");
    Console.ForegroundColor = ConsoleColor.White;
}
Reference
  1. MSJO.kr, “Qt Concurrent Example”
  2. oreilly.com, “Concurrency: An Overview”
  3. gavilanch3, “Using Task.WhenAll - Avoid Inefficient Code” / gavilanch3, “Parallel.ForEachAsync - Concurrent Tasks with a Limit”

Prεv(Θld)  
Content
Search     RSS Feed     BY-NC-ND