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하는 것이 더 부드럽겠습니다. ^^
정성태

... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923184오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921708.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920550개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921051개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201916990오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916807오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916498오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918253개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926126개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919049오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919244오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924449개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918891오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920616오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918908오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919673오류 유형: 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/201922741오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922025Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920064VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916445오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919850Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918097오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916963오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918312.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915609오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920791오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...