C#에서 Thread로 timeout구현을 해보았다.
Join을 호출하면 파라미터로 주어진 시간동안 현재 스레드가 정지하게 되므로 유의하자.
(Join을 호출시 그 시간이 넘었더라고 해도 대상 스레드는 abort되지 않는다.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Timeout | |
{ | |
static void Main(string[] args) | |
{ | |
Thread thread = new Thread(() => | |
{ | |
Thread.Sleep(2000); | |
Console.WriteLine("Worked!"); | |
}); | |
thread.Start(); | |
if (!thread.Join(1000)) | |
{ | |
thread.Abort(); | |
Console.WriteLine("Timeout!"); | |
} | |
} | |
} |
class로 만들어 쓰자면 이정도가 될 듯 하다.
'언어 > C#' 카테고리의 다른 글
[C#] 공변성과 반공변성이란? (0) | 2018.04.21 |
---|---|
[C#] 동기적 재시도(Retry) 함수 구현하기 (0) | 2017.01.10 |