Microsoft MVP성태의 닷넷 이야기
.NET Framework: 538. Thread.Abort로 인해 프로세스가 종료되는 현상 [링크 복사], [링크+제목 복사],
조회: 18804
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 11개 있습니다.)
디버깅 기술: 6. .NET 예외 처리 정리
; https://www.sysnet.pe.kr/2/0/316

디버깅 기술: 15. First-Chance Exception
; https://www.sysnet.pe.kr/2/0/510

디버깅 기술: 16. Watson Bucket 정보를 이용한 CLR 응용 프로그램 예외 분석
; https://www.sysnet.pe.kr/2/0/595

.NET Framework: 110. WPF - 전역 예외 처리
; https://www.sysnet.pe.kr/2/0/614

디버깅 기술: 42. Watson Bucket 정보를 이용한 CLR 응용 프로그램 예외 분석 - (2)
; https://www.sysnet.pe.kr/2/0/1096

.NET Framework: 534. ASP.NET 응용 프로그램이 예외로 프로세스가 종료된다면?
; https://www.sysnet.pe.kr/2/0/10863

.NET Framework: 538. Thread.Abort로 인해 프로세스가 종료되는 현상
; https://www.sysnet.pe.kr/2/0/10867

디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상
; https://www.sysnet.pe.kr/2/0/11383

디버깅 기술: 119. windbg 분석 사례 - 종료자(Finalizer)에서 예외가 발생한 경우 비정상 종료(Crash) 발생
; https://www.sysnet.pe.kr/2/0/11732

닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
; https://www.sysnet.pe.kr/2/0/13422

닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
; https://www.sysnet.pe.kr/2/0/13551




Thread.Abort로 인해 프로세스가 종료되는 경우

"제프리 리처의 CLR via C#" 책을 보면,

제프리 리처의 CLR via C#
; http://www.yes24.com/24/goods/15169403

675페이지에 다음과 같은 내용이 있습니다.

CLR은 스레드가 ThreadAbortException을 발생시키도록 한다. ... 다른 예외와는 다르게 ThreadAbortException은 처리되지 않아도 응용 프로그램을 종료시키지 않는다. CLR은 이 예외를 조용히 먹어버리고 해당 스레드를 종료시킨다.


이는 다음과 같은 코드로 재현해 볼 수 있는데요.

using System;
using System.IO;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        ThrowException();
    }

    private static void ThrowException()
    {
        EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset);
        EventWaitHandle waitForever = new EventWaitHandle(false, EventResetMode.ManualReset);

        Thread t1 = new Thread(() =>
            {
                ewh.Set();

                try
                {
                    // throw new ApplicationException("Exception occurred!!!");
                    waitForever.WaitOne();
                } catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
           });

        t1.Start();

        ewh.WaitOne();
        t1.Abort();
        t1.Join();
    }
}

외부 스레드에서 t1.Abort를 호출해 ThreadAbortException을 발생시켰고, 내부의 try/catch 메시지가 실행되는 걸로 확인할 수 있지만 분명히 프로그램은 종료되지 않습니다. (legacyUnhandledExceptionPolicy 속성 값이 false여도 종료가 안됩니다.)




그런데, 예외적인 상황이 하나 있습니다. 바로 ASP.NET의 "요청을 처리하는 스레드"를 외부에서 강제로 Thread.Abort 시킨 경우입니다.

재현은 ASP.NET 웹 폼 프로젝트를 만들고 다음과 같이 코딩을 하면 확인할 수 있습니다.

using System;
using System.Threading;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread currentThread = Thread.CurrentThread;

            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

            Thread t1 = new Thread((objThread) =>
            {
                Thread requestThread = objThread as Thread;

                requestThread.Abort(); // Button1_Click 메서드를 실행하는 스레드를 종료,
                                       // 원치 않게 프로세스도 함께 종료됨.
                ewh.Set();
            });

            t1.Start(currentThread);
            ewh.WaitOne();
        }
    }
}

여기서 궁금한 점이 하나 생깁니다. 그렇다면 동일하게 ThreadAbortException을 발생시키는 Response.End를 호출하는 경우에는 왜 프로세스가 종료되지 않느냐는 점입니다. 이것에는 ASP.NET 내부의 배려가 있음을 Response.End 메서드를 .NET Reflector를 이용해 소스 코드를 보면 알아낼 수 있습니다.

// HttpResponse 타입의 End 메서드
public void End()
{
    if (this._context.IsInCancellablePeriod)
    {
        AbortCurrentThread();
    }
    else
    {
        this._endRequiresObservation = true;
        if (!this._flushing)
        {
            this.Flush();
            this._ended = true;
            if (this._context.ApplicationInstance != null)
            {
                this._context.ApplicationInstance.CompleteRequest();
            }
        }
    }
}

[SecurityPermission(SecurityAction.Assert, ControlThread=true)]
private static void AbortCurrentThread()
{
    Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}

보는 바와 같이, HttpApplication.CancelModuleException 타입의 인스턴스를 넘기는 차이가 있는데 정말 이것으로 인해 비정상 종료가 되지 않는지 다음과 같은 코드를 통해 확인해 볼 수 있습니다.

using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Threading;
using System.Web;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread currentThread = Thread.CurrentThread;
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

            Thread t1 = new Thread((objThread) =>
            {
                Thread requestThread = objThread as Thread;

                Assembly asm = Assembly.GetAssembly(typeof(HttpApplication));
                ObjectHandle instance = AppDomain.CurrentDomain.CreateInstance(asm.FullName, "System.Web.HttpApplication+CancelModuleException", false, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { false }, null, null);
                object objValue = instance.Unwrap();

                requestThread.Abort(objValue);
                ewh.Set();
            });

            try
            {
                t1.Start(currentThread);

                while (true)
                {
                    System.Diagnostics.Trace.WriteLine("ThreadID: " + AppDomain.GetCurrentThreadId());
                    Thread.Sleep(500);
                }
            } catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
        }
    }
}

실행해 보면, 이번에는 해당 요청을 실행하는 스레드는 ThreadAbortException과 함께 처리를 중지하지만 w3wp.exe (또는 iisexpress.exe)는 종료하지 않고 실행이 계속됩니다.

역시, 내부를 살펴보면 System.Web.HttpApplication 타입의 ExecuteStep 메서드에서 CancelModuleException 인스턴스가 설정된 ThreadAbortException 예외에 대해서는 Thread.ResetAbort를 호출함으로써 예외 전파를 중지하고 있음을 볼 수 있습니다.

internal Exception ExecuteStep(IExecutionStep step, ref bool completedSynchronously)
{
    Exception exception = null;
    try
    {
        try
        {
            if (step.IsCancellable)
            {
                this._context.BeginCancellablePeriod();
                try
                {
                    step.Execute();
                }
                finally
                {
                    this._context.EndCancellablePeriod();
                }
                this._context.WaitForExceptionIfCancelled();
            }
            else
            {
                step.Execute();
            }
            if (!step.CompletedSynchronously)
            {
                completedSynchronously = false;
                return null;
            }
        }
        // ...[생략]...
    }
    catch (ThreadAbortException exception4)
    {
        if ((exception4.ExceptionState != null) && (exception4.ExceptionState is CancelModuleException))
        {
            if (((CancelModuleException) exception4.ExceptionState).Timeout)
            {
                exception = new HttpException(SR.GetString("Request_timed_out"), null, 0xbb9);
                PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_TIMED_OUT);
            }
            else
            {
                exception = null;
                this._stepManager.CompleteRequest();
            }
            Thread.ResetAbort();
        }
    }
    completedSynchronously = true;
    return exception;
}




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







[최초 등록일: ]
[최종 수정일: 10/18/2015]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232115오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232416개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232233개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232123오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232201개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232340닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233012닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232316개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232711개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232376개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232628닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232321닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232417닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232234개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232512닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232251C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232362Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232686닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232455닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232342닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232454오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232620닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232361개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232496닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...