티스토리 뷰
앞 예제에서는 Monitor 클래스를 사용해서 object를 lock 시켰다.
이번에는 lock keyword를 사용해보자.
lock keyword를 사용하면 Monitor를 사용하는 것보다 안전하고 간편하게 thread를 사용할 수 있다.
아래 예제를 보자.
예제에서 보면 Monitor.Enter 와 Monitor.Exit 대신 lock 블럭으로 감싸준 것을 알 수 있다.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ThreadSample
{
class Program
{
private static Queue<string> myQueue = new Queue<string>();
static void Main(string[] args)
{
ThreadStart myThreadStart = new ThreadStart(DoWork);
Thread myThread = new Thread(myThreadStart);
myThread.Start();
for (int count = 0; count < 300; count++)
{
lock (myQueue)
{
Console.Write("-");
myQueue.Enqueue("-");
}
}
lock (myQueue)
{
foreach (string item in myQueue)
{
Console.Write(item + " ");
}
}
}
public static void DoWork()
{
for (int count = 0; count < 1000; count++)
{
lock (myQueue)
{
Console.Write(".");
myQueue.Enqueue(".");
}
}
}
}
}
실행 결과 화면은 아래와 같다.
앞 예제와 마찬가지로 foreach 문이 완료된 후에, 다른 thread가 계속 실행되고 있음을 알 수 있다.
이번에는 lock keyword를 사용해보자.
lock keyword를 사용하면 Monitor를 사용하는 것보다 안전하고 간편하게 thread를 사용할 수 있다.
아래 예제를 보자.
예제에서 보면 Monitor.Enter 와 Monitor.Exit 대신 lock 블럭으로 감싸준 것을 알 수 있다.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ThreadSample
{
class Program
{
private static Queue<string> myQueue = new Queue<string>();
static void Main(string[] args)
{
ThreadStart myThreadStart = new ThreadStart(DoWork);
Thread myThread = new Thread(myThreadStart);
myThread.Start();
for (int count = 0; count < 300; count++)
{
lock (myQueue)
{
Console.Write("-");
myQueue.Enqueue("-");
}
}
lock (myQueue)
{
foreach (string item in myQueue)
{
Console.Write(item + " ");
}
}
}
public static void DoWork()
{
for (int count = 0; count < 1000; count++)
{
lock (myQueue)
{
Console.Write(".");
myQueue.Enqueue(".");
}
}
}
}
}
실행 결과 화면은 아래와 같다.
앞 예제와 마찬가지로 foreach 문이 완료된 후에, 다른 thread가 계속 실행되고 있음을 알 수 있다.
'Code > C#' 카테고리의 다른 글
Thread Join 사용법과 예제 (0) | 2007.12.08 |
---|---|
Thread Abort 사용법과 예제 (0) | 2007.12.08 |
Thread & Monitor 사용 방법과 예제 (0) | 2007.12.08 |
[C#] C# 2.0 스타일 Thread 사용법과 예제 (0) | 2007.12.08 |
[C#] Thread 샘플 코드 4 (0) | 2007.12.08 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- AdSense감추기
- AxWebBrowser
- 유틸리티
- autohotkey
- Sample Code
- READYSTATE_COMPLETE
- Microsoft
- Service pack
- download.com
- jre
- iText
- ScreenHunter
- registry
- java
- 스크린캡쳐
- WinAutomation
- 애드센스감추기
- .net framework
- tagREADYSTATE
- Rollback Rx
- DotNetMagic
- Automation
- c#
- windows
- iTextSharp
- 애드센스숨기기
- AdSense숨기기
- Regular Expressions
- Phalanger
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함