DevSight

Concurrency in C# Example

C#, .NET 프로그램에 사용할 수 있는 라이브러리 및 언어 기능을 사용하면 동시성(Concurrency) 구현을 쉽게 할 수 있다. 동시성 개요1를 다시 정리해 보면 다음과 같다.

  • Concurrency : Doing more than one thing at a time. (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. (Async-Await-Task Example)
  • Reactive Programming : A declarative style of programming where the application reacts to events.

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

일반 비동기 방식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
Read More ···