Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 5개 있습니다.)
.NET Framework: 486. Java의 ScheduledExecutorService에 대응하는 C#의 System.Threading.Timer
; https://www.sysnet.pe.kr/2/0/1823

VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드
; https://www.sysnet.pe.kr/2/0/11090

.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점
; https://www.sysnet.pe.kr/2/0/11134

Windows: 189. WM_TIMER의 동작 방식 개요
; https://www.sysnet.pe.kr/2/0/12539

.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교
; https://www.sysnet.pe.kr/2/0/13069




System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점

이전에도 설명했지만, System.Threading.Timer는 그 기반을 Win32 API인 CreateTimerQueueTimer 함수에 두고 있습니다.

C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드
; https://www.sysnet.pe.kr/2/0/11090

이 때문에 GC가 있긴 해도 System.Threading.Timer는 IDisposable을 구현하고 있으므로 가능한 Dispose를 명시적으로 불러주는 게 자원 관리상 좋습니다. 결국, 다음과 같이 코딩할 수 있는데요.

using System;

class Program
{
    static void Main(string[] args)
    {
        new WorkItem(5, 0);
        Console.ReadLine();
    }

    class WorkItem
    {
        public int Arg;
        System.Threading.Timer _timer;

        public WorkItem(int arg, int interval)
        {
            Arg = arg;
            _timer = new System.Threading.Timer(timerCallback, this, interval, 0);
        }

        private static void timerCallback(object state)
        {
            WorkItem workItem = state as WorkItem;

            if (workItem == null)
            {
                return;
            }

            if (workItem._timer == null)
            {
#if DEBUG
                throw new ApplicationException("workItem._timer == null");
#else
                return;
#endif
            }

            workItem._timer.Dispose();
        }
    }
}

위의 코드는 C++에서 설명했던 것과 유사한 문제에 빠집니다. 즉, _timer 변수에 값이 들어가는 것과, "new System.Threading.Timer"로 인해 타이머 대기 작업이 큐에 들어가 실행되는 시점이 차이가 발생한다는 점입니다. 경우에 따라, timerCallback 메서드가 실행되는 시점에 아직 _timer 변수가 초기화되지 않는 경우가 있습니다. (실제로, 제가 만든 응용 프로그램에서 아주 가끔씩 발생합니다.)

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




첨언하자면, 이 글의 예제에서 사용한 타이머 대기 작업 사용 방법은,

new System.Threading.Timer(timerCallback, this, 0, 0);

결국 다음의 작업과 동일한 것입니다.

ThreadPool.QueueUserWorkItem(workFunc, 6);

static void workFunc(object state)
{
    Console.WriteLine(state);
}

따라서 System.Threading.Timer의 마지막 2개의 인자에 0, 0을 지정하는 것이라면 ThreadPool.QueueUserWorkItem을 사용하는 것이 더 안전합니다.

하지만, 그 외의 경우라면 어떻게 해서든 안전하게 실행시켜야 할 텐데요. 그때는 어쩔 수 없을 것 같습니다. 다음과 같은 식으로 약간의 조악한 안전장치를 넣어두어야겠지요.

private static void timerCallback(object state)
{
    WorkItem workItem = state as WorkItem;

    try
    {
        if (workItem == null)
        {
            return;
        }

        int tryCount = 5;
        while (workItem._timer == null && tryCount-- > 0)
        {
            Thread.Sleep(10);
        }

        if (workItem._timer == null)
        {
#if DEBUG
                throw new ApplicationException("workItem._timer == null");
#else
                return;
#endif
        }

        Console.WriteLine(workItem.Arg);

        workItem._timer.Dispose();
    }
    catch
    {
        return;
    }
}

혹시 더 좋은 의견 있으신 분은 덧글 부탁드립니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/3/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2017-01-21 08시53분
[spowner] timer 필드에 Timer 인스턴스가 들어가기 전에 timerCallback 메소드가 호출되는 경험을 하셨다는 것은 좀 놀랍네요... 덕분에 그럴 수 있다는 것을 지금에야 자각했습니다.

만약 timer 인스턴스를 생성하는 곳과 timerCallback을 처리하는 것이 WorkItem에서 이루어지는 것이라면, ResetEvent를 사용하는게 while-Sleep 보다는 낫지 않을까 하는 의견 내봅니다
[guest]
2017-01-21 08시54분
[spowner] 또는 lock도 괜찮을 것 같습니다
[guest]
2017-01-21 11시04분
[ryujh] 안녕하세요. 생성자에서 interval과 0 를 지정해야 하는지는 모르겠지만
아래의 코드로 바꾸면 되지 않을까하는 제 생각입니다.

수정 전
            _timer = new System.Threading.Timer(timerCallback, this, interval, 0);
수정 후
            _timer = new System.Threading.Timer(timerCallback, this, Timeout.Infinite, Timeout.Infinite);
            _timer.Change(interval, 0);
[guest]
2017-01-21 11시30분
[spowner] @ryujh !! ^^
[guest]
2017-01-22 03시07분
오... ryujh님 의견대로 Change하는 것이 더 부드럽겠습니다. ^^
정성태

... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11823정성태2/21/201913515오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911648오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912102오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915248오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913917Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912842VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199992오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912499Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911387오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910210오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911817.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199635오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913429오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911494.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201913003.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201914061디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912364Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201912132디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913965.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201912015Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911491디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912883.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913917개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813198오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813999.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813237개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...