AutoResetEvent, ManualResetEvents는 여러 개의 스레드가 서로 방해를 받지 않고, 신호를 통해 스레드를를 작동 할 수 있습니다.
밑의 그림에서 보시는 것 처럼
신호에 따라 스레드가 대기하거나,
신호에 따라 스레드를 실행할 수 있습니다.
AutoResetEvent는 사용자의 여러 개의 스레드 실행하면 하나의 스레드가 끝날 때까지 기다렸다가 대기하고, 하나의 스레드가 끝나면 다음 스레드가 실행됩니다.
ManualResetEvent는 여러 개의 스레드가 한번에 실행됩니다.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EvnetWaitHandleSample
{
class Program
{
public static EventWaitHandle _waitHandle;
static void Main(string[] args)
{
Threading t = new Threading();
Thread.Sleep(1000);
Console.ReadKey();
}
}
class Threading
{
private int count = 0;
public static EventWaitHandle _waitHandle;
public Threading()
{
Console.Write("1:AutoResetEvent\t 2:ManualResetEvent - ");
switch (Console.ReadKey().KeyChar)
{
case '1':
_waitHandle = new AutoResetEvent(true);
break;
case '2':
_waitHandle = new ManualResetEvent(true);
break;
}
Console.WriteLine("");
Thread T1 = new Thread(new ThreadStart(Work));
Thread T2 = new Thread(new ThreadStart(Work));
Thread T3 = new Thread(new ThreadStart(Work));
Thread T4 = new Thread(new ThreadStart(Work));
T1.Start();
T2.Start();
T3.Start();
T4.Start();
}
private void Work()
{
_waitHandle.WaitOne();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(count++);
Thread.Sleep(1000);
}
_waitHandle.Reset();
}
}
}
01
AutoResetEvent는 여러 개의 스레드를 실행하더라도 처음 시작된 스레드만 실행되고 나머지는 대기 하고 있습니다. 그리고 첫 스레드가 끝날때 Reset() 신호로 인해 그 다음 스레드가 실행되지 않고 무한정 대기 합니다.
ManualResetEvent는 여러 개의 스레드가 동시에 실행되기 때문에 Reset() 신호를 날려도 벌써 모든 스레드가 해야 할 일이 끝난 상태라서 대기할 스레드가 없습니다.
밑의 소스를 수정하시면 AutoResetEvent 일 때 1초 간격으로 19까지 출력됩니다.
private void Work()
{
_waitHandle.WaitOne();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(count++);
Thread.Sleep(1000);
}
_waitHandle.Set();
}
참고 - CodeProject
'프로그래밍 > .NET' 카테고리의 다른 글
| [C#, MySQL]CSV파일의 데이터를 DB Export (0) | 2013.02.07 |
|---|---|
| [C#]ThreadPool (0) | 2013.02.05 |
| [ASP.NET]ASP.NET에서 WebBrowser(윈폼) 사용하기 (0) | 2013.02.04 |
| [C#] MySQL 사용 (0) | 2013.01.29 |
| [C#] HTTP/HTTPS 송수신 (HttpWebRequest/HttpWebResponse) (2) | 2013.01.18 |