다음 소스는 Stopwatch를 이용하여 마이크로세컨드 단위로 대기 하는 클래스를 만들어 보았습니다. (물론, CPU 점유 버젼입니다)
다른 분들께 참고하시라고 공유 드립니다.
사용법은 다음과 같습니다.
var w = Wait.Start(1000000); // 1000000 마이크로초(1초) 대기
// .. 다른 코드 : 다른 코드가 실행하면서 발생하는 지연도 반영하기 위함
w.Sleep();
---------------------------------------------------------------------------------------------------
public class Wait
{
private static bool isHighResolution;
private static long frequency;
private ManualResetEvent re;
private Stopwatch sw;
private long ticks;
private long finalTicks;
static Wait()
{
isHighResolution = Stopwatch.IsHighResolution;
frequency = Stopwatch.Frequency;
}
protected Wait(long microseconds)
{
re = new ManualResetEvent(false);
sw = Stopwatch.StartNew();
if (isHighResolution == false)
throw new NotSupportHighResolutionException("System is not support high resolution frequency.");
ticks = microseconds * frequency / 1000000;
}
public static Wait Start(long microseconds)
{
Wait result = new Wait(microseconds);
return result;
}
public void Sleep()
{
while (sw.ElapsedTicks <= ticks)
;// Thread.SpinWait(100);
//Thread.Sleep(1);
//re.WaitOne(1);
finalTicks = sw.ElapsedTicks;
}
public long TotalMicroseconds
{
get
{
return finalTicks * 1000000 / frequency;
}
}
}
public class NotSupportHighResolutionException : Exception
{
public NotSupportHighResolutionException(string msg)
: base(msg)
{
}
}
[최초 등록일: ]
[최종 수정일: 4/18/2015]