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

비밀번호

댓글 작성자
 




... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12406정성태11/8/202012980.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010474.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202010981.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011041.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011620.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010545VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207576오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011211.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209686오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/20209818.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208189VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209506오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20207922오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208394오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012542.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010703디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010580.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/20209970오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010732.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202010991Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20208744오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/20209957오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202010946.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208552오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010225VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207697오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...