Microsoft MVP성태의 닷넷 이야기
.NET Framework: 354. x64 - AspCompat과 STA COM 개체가 성능에 미치는 영향 [링크 복사], [링크+제목 복사],
조회: 14432
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

x64 - AspCompat과 STA COM 개체가 성능에 미치는 영향

지난번에 x86에서 이 상황을 테스트 한 결과를 설명했는데요.

x86 - AspCompat과 STA COM 개체가 성능에 미치는 영향
; https://www.sysnet.pe.kr/2/0/1394

재미있게도, x64 프로세스에서는 상황이 달라집니다. 우선, AspCompat=true와 Page_Load에서 x64 STA COM 개체를 생성한 경우를 한번 볼까요?

// ==== default.aspx ====
<%@ Page AspCompat="true" Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

	... [HTML 생략]...

// ==== default.aspx.cs ====
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            WebTestHelperLib.ComAptTestClass catc = new WebTestHelperLib.ComAptTestClass();

            catc.DoMethod();
        }
    }
}

default.aspx.cs 코드를 다음과 같이 변경시키고,

protected void Page_Load(object sender, EventArgs e)
{
    int tid;
    WebTestHelperLib.ComAptTestClass catc = new WebTestHelperLib.ComAptTestClass();
    int aptKind = catc.DoMethod3(5, out tid);

    StringBuilder sb = new StringBuilder();

    sb.AppendFormat("ctor Thread: {0}<br />", _pageTid);
    sb.AppendFormat("ctor Apt: {0}<br />", GetCurrentApt());
    sb.AppendFormat("Page_Load Thread: {0}<br />", AppDomain.GetCurrentThreadId());
    sb.AppendFormat("Page_Load Thread Apt: {0}<br />", GetCurrentApt());
    sb.AppendFormat("Com Thread: {0}<br />", tid);
    sb.AppendFormat("Com Apt: {0}<br />", aptKind);

    Label1.Text = sb.ToString();
}

public int GetCurrentApt()
{
    FieldInfo fieldInfo = typeof(Thread).GetField("DONT_USE_InternalThread", BindingFlags.NonPublic | BindingFlags.Instance);
    IntPtr objValue = (IntPtr)fieldInfo.GetValue(Thread.CurrentThread);

    if (IntPtr.Size == 4)
    {
        IntPtr teb = new IntPtr(Marshal.ReadInt32(objValue, 16 * 4));

        IntPtr reservedForOle = new IntPtr(teb.ToInt64() + 0xf80);
        long ReservedForOle = Marshal.ReadInt64(reservedForOle); // TEB.ReservedForOle
        if (ReservedForOle == 0)
        {
            return -1;
        }

        IntPtr pNativeApt = new IntPtr(ReservedForOle + 0x50);
        long NativeApt = Marshal.ReadInt64(pNativeApt); // SOleTlsData.pNativeApt

        IntPtr pAptKind = new IntPtr(NativeApt + 0x0c);
        int AptKind = Marshal.ReadInt32(pAptKind); // CComApartment._AptKind

        return AptKind;
    }
    else
    {
        IntPtr teb = new IntPtr(Marshal.ReadInt64(objValue, 16 * 6));
        IntPtr reservedForOle = new IntPtr(teb.ToInt64() + 0x1758);
        long ReservedForOle = Marshal.ReadInt64(reservedForOle); // TEB.ReservedForOle
        if (ReservedForOle == 0)
        {
            return -1;
        }

        IntPtr pNativeApt = new IntPtr(ReservedForOle + 0x80);
        long NativeApt = Marshal.ReadInt64(pNativeApt); // SOleTlsData.pNativeApt

        IntPtr pAptKind = new IntPtr(NativeApt + 0x10);
        int AptKind = Marshal.ReadInt32(pAptKind); // CComApartment._AptKind

        return AptKind;
    }
}

COM 개체에서 제공되는 DoMethod3 메서드에도 x64에 대한 고려를 추가합니다.

STDMETHODIMP CComAptTest::DoMethod3(LONG sleepSecond,LONG *tid, LONG *aptKind)
{
    ::Sleep(sleepSecond * 1000);

    *tid = ::GetCurrentThreadId();

    do 
    {
#if defined(_AMD64_)
        BYTE *pTeb = (BYTE *)NtCurrentTeb();
        __int64 *pOle = (__int64 *)(pTeb + 0x1758);

        if (*pOle == 0)
        {
            printf("No apartment\n");
            break;
        }

        __int64 *pNativeApt = (__int64 *)(*pOle + 0x80);
        *aptKind = *(int *)(*pNativeApt + 0x10);

#elif defined(_X86_)
        BYTE *pTeb = (BYTE *)NtCurrentTeb();
        int *pOle = (int *)(pTeb + 0xf80);

        if (*pOle == 0)
        {
            printf("No apartment\n");
            break;
        }

        int *pNativeApt = (int *)(*pOle + 0x50);
        *aptKind = *(int *)(*pNativeApt + 0x0c);

#endif
    } while (false);

    return S_OK;
}

자... 이렇게 하고 2개의 요청을 동시에 보내면 다음과 같은 결과를 얻을 수 있습니다.

ctor Thread: 34124
ctor Apt: 4
Page_Load Thread: 7836
Page_Load Thread Apt: 4
Com Thread: 7836
Com Apt: 4

ctor Thread: 27452
ctor Apt: 4
Page_Load Thread: 7836
Page_Load Thread Apt: 4
Com Thread: 7836
Com Apt: 4

오... 뭔가 바뀌지 않았나요? ctor Apt == 4 == STA인데요. 처음 요청을 34124, 27452 스레드로 받고 있는데 이것들이 모두 STA 스레드로 초기화되어 있습니다. 여기서 유추해 볼 수 있는 것은 STA COM 개체를 가진 웹 페이지를 처리할 수 있는 전용 STA 스레드 풀을 가지는 것으로 보입니다.

비록 STA로 초기화된 스레드 풀이긴 하지만 COM 개체가 멀티스레드 용이 아니기 때문에 다시 전용 7836 STA 스레드에 COM 메서드 호출을 직렬화하고 있습니다.

x64부터는, AspCompat=True로 지정한 웹 페이지와 그렇지 않은 웹 페이지들에 대해 각각 별도의 스레드 풀을 제공하고 있는 것입니다.




AspCompat=True 값을 설정하지 않은 경우에는 0x80004002 예외가 발생하므로 생략합니다.




AspCompat=True인 경우, STA COM 개체를 Page_Load가 아닌 생성자나 멤버 변수 정의 시에는 어떨까요? 다음은 그 결과입니다.

ctor Thread: 29200
ctor Apt: 4
Page_Load Thread: 13888
Page_Load Thread Apt: 4
Com Thread: 7836
Com Apt: 4

ctor Thread: 35820
ctor Apt: 4
Page_Load Thread: 13888
Page_Load Thread Apt: 4
Com Thread: 7836
Com Apt: 4

이것 역시 x86과 유사한 결과를 가지지만, 다른 점이 있다면 맨 처음 요청을 처리하는 ctor 스레드가 STA로 초기화된 스레드 풀의 스레드라는 점입니다. 덕분에 STA COM 개체를 Page_Load 이전 단계에서 생성한다고 해도 MTA를 위한 웹 페이지들의 요청에는 영향을 주지 않습니다. 게다가 STA 스레드 풀을 별도로 운영하여 사용자의 요청을 받아들이고는 곧바로 별도의 STA 스레드(위에서는 13888)로 요청을 전달하고는 다음 사용자의 요청을 곧바로 받아들이게 됩니다. 따라서, x86에서 발생했던 스레드 풀 고갈 현상이 x64에서는 발생하지 않습니다.




결론을 내려보면, x64에서는 COM 개체의 생성을 어느 때 해도 전체적인 성능에는 크게 영향을 미치지는 않습니다.

하지만, COM 개체가 기왕이면 MTA로 만들어지는 것이 전체적인 페이지 반응 속도 향상에 도움이 된다는 사실에는 변함이 없습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/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)
13388정성태7/3/20233693오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233756오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233822Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20234043Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233757.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233510개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233578.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233981오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233405스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233437스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233331오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237219오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233567.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233237스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233333오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234645오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233263개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233336개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233494개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233306개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233466개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233606오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233335.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233079오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233919.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233506스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...