Microsoft MVP성태의 닷넷 이야기
.NET Framework: 538. Thread.Abort로 인해 프로세스가 종료되는 현상 [링크 복사], [링크+제목 복사],
조회: 18807
글쓴 사람
정성태 (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)
13541정성태1/29/20241980VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242117Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242372개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242428닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242542닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242603닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242487닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242261닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242490닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242368닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242290닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242213닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242096닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242235Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242158오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242245닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242211오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242300오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242100오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242242닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242305닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242077오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242136닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242386닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242219스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242344닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...