Microsoft MVP성태의 닷넷 이야기
.NET Framework: 538. Thread.Abort로 인해 프로세스가 종료되는 현상 [링크 복사], [링크+제목 복사]
조회: 18693
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12093정성태12/26/201910945.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910338디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201911835디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910498.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911192디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910152Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201910634디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201912641디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910375오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201911023디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201912338Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201912110오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201913818개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201911825.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201912947오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201912982Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201912464Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201910689디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
12075정성태12/11/201911548디버깅 기술: 141. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅
12074정성태12/10/201911146디버깅 기술: 140. windbg/Visual Studio - 값이 변경된 경우를 위한 정지점(BP) 설정(Data Breakpoint)
12073정성태12/10/201912993Linux: 24. Linux/C# - 실행 파일이 아닌 스크립트 형식의 명령어를 Process.Start로 실행하는 방법
12072정성태12/9/201910303오류 유형: 583. iisreset 수행 시 "No such interface supported" 오류
12071정성태12/9/201912718오류 유형: 582. 리눅스 디스크 공간 부족 및 safemode 부팅 방법
12070정성태12/9/201914807오류 유형: 581. resize2fs: Bad magic number in super-block while trying to open /dev/.../root
12069정성태12/2/201911231디버깅 기술: 139. windbg - x64 덤프 분석 시 메서드의 인자 또는 로컬 변수의 값을 확인하는 방법
12068정성태11/28/201914424디버깅 기술: 138. windbg와 Win32 API로 알아보는 Windows Heap 정보 분석 [3]파일 다운로드2
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...