Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)

문제 재현 - Managed Debugging Assistant 'DisconnectedContext' has detected a problem in '...'

비주얼 스튜디오로 디버깅 시 다음과 같은 예외가 발생한다면?

Managed Debugging Assistant 'DisconnectedContext' has detected a problem in 'C:\...\ConsoleApplication1\bin\x86\Debug\ConsoleApplication1.exe'.

Additional information: Transition into COM context 0xdd0138 for this RuntimeCallableWrapper failed with the following error: The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED)). This is typically because the COM context 0xdd0138 where this RuntimeCallableWrapper was created has been disconnected or it is busy doing something else and cannot process the context transition. No proxy will be used to service the request on the COM component and calls will be made to the COM component directly. This may cause corruption or data loss. To avoid this problem, please ensure that all COM contexts/apartments/threads stay alive and are available for context transition, until the application is completely done with the RuntimeCallableWrappers that represents COM components that live inside them.


아래의 문서에 따라 원인을 짐작할 수 있습니다.

disconnectedContext MDA
; https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/disconnectedcontext-mda

말 그대로 다음의 원인 때문입니다.

The OLE apartment or context has been shut down when the CLR attempts to transition into it. This is most commonly caused by STA apartments being shut down before all the COM components owned by the apartment were completely released. This can occur as a result of an explicit call from user code on an RCW or while the CLR itself is manipulating the COM component, for example when the CLR is releasing the COM component when the associated RCW has been garbage collected.


문제를 이해하기 위해 간단한 재현 프로그램을 만들어 보면 좋겠는데요. 막상 재현하려니 또 잘 안나는군요. ^^; 그래도 다소 억지스럽게 재현 코드를 쉽게 구성해 볼 수는 있습니다. 우선, ATL COM 프로젝트를 만들어 다음의 메서드만 하나 구현해 줍니다.

STDMETHODIMP CSimpleObject::DoDelay(LONG seconds)
{
    wprintf(L"DoDelay started!");
    Sleep(seconds * 1000);
    wprintf(L"DoDelay ended!");
    return S_OK;
}

그리고 이 COM 객체를 C# 콘솔 프로젝트에서 다음과 같이 사용해 줍니다.

using System.Threading;

namespace ConsoleApplication1
{
    public class Program
    {
        static ATLProject1Lib.SimpleObjectClass _so;

        static void Main(string[] args)
        {
            ApartmentState aptState = ApartmentState.STA;

            Thread t1 = new Thread(threadFunc1);
            t1.ApartmentState = aptState;
            t1.Start();

            Thread.Sleep(2000);

            Thread t2 = new Thread(threadFunc2);
            t2.ApartmentState = aptState;
            t2.Start();

            t1.Join();
            t2.Join();
        }

        private static void threadFunc1()
        {
            _so = new ATLProject1Lib.SimpleObjectClass();
            Thread.Sleep(5000);
        }

        private static void threadFunc2()
        {
            try
            {
                _so.DoDelay(5);
            } catch { }
        }
    }
}

위의 예제가 억지스러운 이유는 COM 객체를 생성한 threadFunc1에 메시지 루프가 없다는 점입니다. 이 때문에 해당 COM 객체를 다른 스레드에서 접근하는 경우 직렬화된 윈도우 메시지를 처리해 주지 않게 되므로 threadFunc2의 _so.DoDelay 호출은 blocking이 걸립니다. (즉, 이런 식으로 쓴다는 것 자체가 말이 안됩니다. 그냥 재현 예제로만 봐주세요.)

결국, ATL COM 객체를 생성했던 STA 스레드가 종료되었지만 t2 스레드에서는 여전히 해당 Apartment에서 생성된 COM 개체를 호출중인 상황이 발생한 것입니다.

이 프로그램을 Visual Studio에서 F5 디버깅을 걸면 "MDA(managed debugging assistant)" 덕분에 "DisconnectedContext" 유형의 상황이 발생했다는 아주 자세한 오류 메시지를 받게 됩니다.

반면, 디버깅을 하지 않으면 try/catch로 인해 예외를 먹는 상황이 됩니다. 혹은 threadFunc2의 try/catch를 하지 않으면 다음과 같은 예외가 발생하는 것을 볼 수 있습니다.

Unhandled Exception: System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.
   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
   at ATLProject1Lib.SimpleObjectClass.DoDelay(Int32 seconds)
   at ConsoleApplication1.Program.threadFunc2() in C:\...\ConsoleApplication1\Program.cs:line 37
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

이처럼, MDA(managed debugging assistant)는 Managed/Unmanaged가 섞인 환경에서 CLR 입장으로써는 파악하기 힘든 문제의 원인을 보다 더 자세하게 알려주는 역할을 합니다. 그래서, 때로는 이 예외가 발생한 경우 무시해도 되고, 무시하지 않아야 하는 경우도 있습니다.

가령, 위에서 DoDelay 메서드는 호출 코드까지는 스레드가 수행했음에도 불구하고 그 이후 작업을 전혀 못하고 예외가 발생한 것입니다. 따라서, 여러분의 코드에서 이 작업의 중요도에 대한 경중에 맞게 예외를 해결하든가, 무시하든가 하면 되는 것입니다.

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

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)
13332정성태4/27/20233870Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233919오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233560Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233759Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233421VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233836VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235259.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234565스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234369.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234298개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235103VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233921개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233893개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234345개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234188개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234263오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233574오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233788Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233883개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233948개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233972Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234473C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234081C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234241.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234147스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233900.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...