Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
.NET Framework: 174. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/841

.NET Framework: 447. w3wp.exe AppPool 재생(recycle)하는 방법 정리
; https://www.sysnet.pe.kr/2/0/1704

개발 환경 구성: 246. IIS 작업자 프로세스의 20분 자동 재생(Recycle)을 끄는 방법
; https://www.sysnet.pe.kr/2/0/1774

.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11145

개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
; https://www.sysnet.pe.kr/2/0/13514

닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
; https://www.sysnet.pe.kr/2/0/13516




작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기

예전 글에 이어,

작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/841

아래의 글은 Global.asax의 Application_End 이벤트 핸들러에서 Recycle의 원인을 알아내는 방법을 설명합니다.

Logging ASP.NET Application Shutdown Events
; https://weblogs.asp.net/scottgu/433194

정리하면, Application_End가 호출되는 시점에 HttpRuntime 객체에 저장된 _shutDownMessage와 _shutDownStack 필드의 값을 .NET Reflection을 이용해 읽어내는 것입니다.

protected void Application_End(object sender, EventArgs e)
{
    HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime",
        BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null);

    if (runtime == null)
        return;

    string shutDownMessage = (string)runtime.GetType().InvokeMember("_shutDownMessage",
        BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);

    string shutDownStack = (string)runtime.GetType().InvokeMember("_shutDownStack",
        BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);

    System.Diagnostics.Trace.WriteLine(String.Format("\r\n\r\n_shutDownMessage={0}\r\n\r\n_shutDownStack={1}",
        shutDownMessage, shutDownStack));
}

위의 예제는 ASP.NET 2.0을 대상으로 하지만, .NET 4.6.1에서도 여전히 잘 동작합니다. 가령, web.config을 변경한 경우 .NET 2.0 기반에서는 다음과 같이 출력 값이 나오고,

_shutDownMessage=CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
HostingEnvironment caused shutdown

_shutDownStack=   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdown()
   at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace)
   at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e)
   at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname)

.NET 4.6.1에서는 이렇게 나옵니다.

_shutDownMessage=IIS configuration change
CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
HostingEnvironment caused shutdown

_shutDownStack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

그런데, Application_End는 Global.asax 이외의 클래스에서는 구독하는 것이 안됩니다. 왜냐하면, End 이벤트가 HttpApplication 객체에는 없기 때문입니다. 따라서 외부 DLL에서 참조하고 싶다면 다음과 같이 HttpContext를 이용해 Disposed 이벤트를 구독해야 합니다.

HttpContext.Current.ApplicationInstance.Disposed += ApplicationInstance_Disposed;

Application_End와 Disposed가 이벤트가 발생하는 시점을 잡아 각각의 Call stack을 확인하면 그 이유를 알 수 있습니다.

// Application_End 호출 시점의 Call stack

>    Test.dll!WebSiteTest.Global.Application_End(object sender, System.EventArgs e) Line 430 C#
    [Native to Managed Transition]  
    System.Web.dll!System.Web.HttpApplication.InvokeMethodWithAssert(System.Reflection.MethodInfo method, int paramCount, object eventSource, System.EventArgs eventArgs) + 0x7a bytes  
    System.Web.dll!System.Web.HttpApplication.ProcessSpecialRequest(System.Web.HttpContext context, System.Reflection.MethodInfo method, int paramCount, object eventSource, System.EventArgs eventArgs, System.Web.SessionState.HttpSessionState session) + 0x126 bytes    
    System.Web.dll!System.Web.HttpApplicationFactory.FireApplicationOnEnd() + 0x6b bytes    
    System.Web.dll!System.Web.HttpApplicationFactory.Dispose() + 0x80 bytes 
    System.Web.dll!System.Web.HttpRuntime.Dispose() + 0x158 bytes   
    System.Web.dll!System.Web.HttpRuntime.ReleaseResourcesAndUnloadAppDomain(object state) + 0x3d bytes 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x15e bytes 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x17 bytes  
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x70 bytes 
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x160 bytes  
    [Native to Managed Transition]  
    [Appdomain Transition]  
    [Native to Managed Transition]  

// Global_Disposed 호출 시점의 Call stack

>    Test.dll!WebSiteTest.Global.Global_Disposed(object sender, System.EventArgs e) Line 425 C#
    System.Web.dll!System.Web.HttpApplication.Dispose() + 0x9f bytes    
    System.Web.dll!System.Web.HttpApplication.DisposeInternal() + 0x30 bytes    
    System.Web.dll!System.Web.HttpApplicationFactory.DisposeHttpApplicationInstances(System.Collections.Stack freeList, ref int numFreeInstances) + 0xf6 bytes  
    System.Web.dll!System.Web.HttpApplicationFactory.Dispose() + 0xd2 bytes 
    System.Web.dll!System.Web.HttpRuntime.Dispose() + 0x158 bytes   
    System.Web.dll!System.Web.HttpRuntime.ReleaseResourcesAndUnloadAppDomain(object state) + 0x3d bytes 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x15e bytes 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x17 bytes  
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x70 bytes 
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x160 bytes  
    [Native to Managed Transition]  
    [Appdomain Transition]  
    [Native to Managed Transition]  

어차피 HttpRuntime.Dispose 메서드를 시작으로 Application_End가 호출된 후 Disposed 이벤트가 발생하기 때문에 HttpRuntime의 _shutDownMessage와 _shutDownStack 필드 값은 동일합니다.

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/16/2017]

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

비밀번호

댓글 작성자
 



2017-02-16 10시00분
[ryujh] 안녕하세요.

본문 중 CONFIG change 와 같이 재시작의 원인이 나외있는데 그 밖에도 Recompile 의 회수(횟수?)가 초과도 원인입니다.

Recompile 이라면 가상경로에서 파일 수정으로 적용하여 발생할 수 있습니다. 쓰기 작업을 가상경로에서 하지 않고 다른 경로에 할 수 있다면 재시작이 적어지니 안정적으로 서비스가 가능할 것입니다.
[guest]
2017-02-22 02시29분
.NET 소스 코드에 Recycle에 대한 이유 몇 가지가 나옵니다.

ApplicationShutdownReason Enum
; https://referencesource.microsoft.com/#system.web/HttpRuntime.cs,4d404925e0f99eb1,references
정성태
2017-02-24 08시04분
[ryujh] 안녕하세요.

이유가 무려 15가지나 되는군요. 15가지 이유 중에 하나로 어플리케이션이 shutdown 될 수 있다는 것인데 안정적인 웹서비스가 어려운지 이제 알겠습니다.

그래서 요즘에는 웹에서 하는 로직을 일부 콘솔프로그램에서 담당하도록 작업 중 입니다.
[guest]
2017-02-25 02시27분
ryujh님, shutdown 될 수 있기는 한데 그래서 더 '안정적인' 경우가 많습니다. ^^ 그리고 recycle 과정 자체가 서비스를 중단 없이 하기 때문에 in-memory Session 같은 것 등을 쓰지 않는 한 서비스 장애로 이어지는 경우는 없습니다.
정성태

... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12442정성태12/4/20207926오류 유형: 691. Visual Studio - Build Events에 robocopy를 사용할때 "Invalid Parameter #1" 오류가 발행하는 경우
12441정성태12/4/20207626오류 유형: 690. robocopy - ERROR : No Destination Directory Specified.
12440정성태12/4/20208658오류 유형: 689. SignTool Error: Invalid option: /as
12439정성태12/4/20209875디버깅 기술: 176. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우 (2) [1]
12438정성태12/2/20209858오류 유형: 688. .Visual C++ - Error C2011 'sockaddr': 'struct' type redefinition
12437정성태12/1/20209420VS.NET IDE: 155. pfx의 암호 키 파일을 Visual Studio 없이 등록하는 방법
12436정성태12/1/20209740오류 유형: 687. .NET Core 2.2 빌드 - error MSB4018: The "RazorTagHelper" task failed unexpectedly.
12435정성태12/1/202015185Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202010499Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/20209570Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
12432정성태11/29/202011031Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR [1]파일 다운로드1
12431정성태11/27/20208958.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/20209655오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/20209727디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208700VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/20209817.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208478오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209485VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/20209916VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202010829.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208651.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208412.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207608오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20208774VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202010847오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208259오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...