Microsoft MVP성태의 닷넷 이야기
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [링크 복사], [링크+제목 복사],
조회: 29741
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 9개 있습니다.)
.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법
; https://www.sysnet.pe.kr/2/0/511

.NET Framework: 92. XmlSerializer 생성자의 실행 속도를 올리는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/521

.NET Framework: 100. XML Serializer를 이용한 값 복사
; https://www.sysnet.pe.kr/2/0/577

.NET Framework: 122. XML Serializer를 이용한 값 복사: 성능은 어떨까!
; https://www.sysnet.pe.kr/2/0/653

.NET Framework: 648. Dictionary<TKey, TValue>를 deep copy하는 방법
; https://www.sysnet.pe.kr/2/0/11157

.NET Framework: 660. Shallow Copy와 Deep Copy
; https://www.sysnet.pe.kr/2/0/11220

.NET Framework: 1141. XmlSerializer와 Dictionary 타입
; https://www.sysnet.pe.kr/2/0/12942

.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
; https://www.sysnet.pe.kr/2/0/13196

.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?
; https://www.sysnet.pe.kr/2/0/13198





XmlSerializer 생성자의 실행 속도를 올리는 방법


지금쯤이면 이미 많은 분들이 아시는 내용이겠지만. 그래도 한번 정리를 해보고 지나가야 할 내용 같아서 써봅니다.

XmlSerializer 생성자에 타입을 전달하는 코드가 처음 실행될 때, 생성자안에서는 타입에 해당하는 직렬화 코드가 이미 있는지를 먼저 찾아보게 됩니다. 만약 없다면, 새롭게 해당 클래스를 직렬화하는 코드를 동적으로 생성해서 로드하게 됩니다.

왜냐하면, 직렬화를 위해서는 반드시 해당 클래스를 일일이 "Reflection"을 통해서 조사해야 하는데, 여기에서 오는 속도 저하가 심각하기 때문에, 아예 처음 한번은 Reflection을 이용해서 직렬화를 해주는 동적 코드를 생성하는 것으로 이 문제를 해결하고 있습니다.

어디... 눈으로 한번 확인해 볼까요?

우선, VS.NET의 "도구" / "옵션" 창에서 "Enable Just My Code" 옵션을 해제하십시오.

그런 다음, 아래와 같은 코드를 작성해서 빌드한 후, 굵은 글씨로 되어 있는 부분에 BP(Break Point)를 설정한 후 "F5" 디버깅 모드로 실행시켜 보십시오.

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
    MyClass myClass = new MyClass();
    XmlSerializer xs = new XmlSerializer(typeof(MyClass)); // BP(Break Point) 설정
  }
}

public class MyClass
{
  public string Prop;
}

"F10" 키를 눌러서 라인을 실행시키면, VS.NET의 "Output" 창에는 다음과 같은 내용이 출력되는 것을 확인할 수 있습니다.

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
'XmlSerializerTest.vshost.exe' (Managed): Loaded '7ptbpl3m', No symbols loaded.

지난 회를 통해서, 우리는 "first chance exception"이 무엇인지 이미 설명을 드렸으니... 이젠 낯설지 않으시죠? ^^

그런데,,, 그냥 호기심 삼아서 위의 예외가 언제 발생하는지 추적해 볼까요?
소스 코드가 없다면 좀 단계가 어렵지만, 마이크로소프트에서 공개하고 있는 "Shared Source CLR"의 XmlSerializer 소스를 살펴보면 그 호기심을 쉽게 풀수가 있습니다.

Shared Source Common Language Infrastructure Archive
; https://github.com/SSCLI

다운로드 받아서, 아래와 같이 XmlSerializer 생성자를 살펴보면 다음과 같은 소스 코드를 확인할 수 있습니다.

.\fx\src\xml\system\xml\serialization\xmlserializer.cs
; https://github.com/SSCLI/sscli20_20060311/blob/master/fx/src/xml/system/xml/serialization/xmlserializer.cs

public XmlSerializer(Type type, string defaultNamespace) {
  if (type == null)
    throw new ArgumentNullException("type");
  this.mapping = GetKnownMapping(type, defaultNamespace);
  if (this.mapping != null) {
    this.primitiveType = type;
    return;
  }
  tempAssembly = cache[defaultNamespace, type];
  if (tempAssembly == null) {
    lock (cache) {
      tempAssembly = cache[defaultNamespace, type];
      if (tempAssembly == null) {
        XmlSerializerImplementation contract;
        Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract);
        if (assembly == null) {

cache에 없으니, TempAssembly.LoadGeneratedAssembly를 이용해서, 관련 직렬화 클래스를 로드해 봅니다. 만약 이때 로드가 안되면(assembly == null) 이후에 동적으로 생성하는 코드가 이어지는데, 여기서는 생략하고 예외가 발생하는 LoadGeneratedAssembly 메서드를 좀 더 추적해 보도록 하겠습니다.

.\fx\src\xml\system\xml\serialization\compilation.cs
; https://github.com/SSCLI/sscli20_20060311/blob/master/fx/src/xml/system/xml/serialization/compilation.cs

internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
{
  Assembly serializer = null;
  contract = null;
  string serializerName = null;
  bool logEnabled = DiagnosticsSwitches.PregenEventLog.Enabled;

  // check to see if we loading explicit pre-generated assembly
  object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
  if (attrs.Length == 0)
  {
    // Guess serializer name: if parent assembly signed use strong name 
    AssemblyName name = GetName(type.Assembly, true);
    serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
    // use strong name 
    name.Name = serializerName;
    name.CodeBase = null;
    name.CultureInfo = CultureInfo.InvariantCulture;
    try
    {
      serializer = Assembly.Load(name);
    }
    catch (Exception e)
    {
      if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
      {
        throw;
      }
      byte[] token = name.GetPublicKeyToken();
      if (token != null && token.Length > 0)
      {
        // the parent assembly was signed, so do not try to LoadWithPartialName
        return null;
      }
#pragma warning disable 618
      serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618

아하, 이 코드들을 보니 답이 나왔군요. ^^ Assembly.Load에서 "first-chance exception(System.IO.FileNotFoundException)"이 한번 발생하고, 이후에 Assembly.LoadWithPartialName에서 다시 한번 내부적으로 "first-chance exception(System.IO.FileNotFoundException)"이 발생하고 있습니다.




이렇게 XmlSerializer의 생성자에 전달되는 Type 하나 당 2번의 예외가 발생합니다. 한 두번 정도야 상관없겠지만, 알게 모르게 참조하는 DLL들 내부에서 이런 초기 예외가 빈번하게 발생하게 되면 눈에 띄는 실행속도 저하가 발생할 수 있습니다. (물론, 일단 한번 cache가 된다면 그 이후에는 빠르게 로드가 되지만.)

그런데, 도대체 어떤 이름의 파일을 로드하려고 시도했던 것일까요? ^^ 해답을 찾을 수 있는 방법을 이미 지난번에 다뤄보았던 "First-Chance Exception" 토픽에서 설명해 놓았으니 이 부분은 건너뛰도록 하겟습니다.

자... 그럼 이 문제를 해결하려면 어떻게 해야 할까요?

간단합니다. ^^ System.IO.FileNotFoundException이 발생하지 않도록 직렬화 관련 클래스를 미리 생성시켜 두면 됩니다. 바로 이런 목적을 위해 "sgen.exe" 파일이 제공되고 있습니다.

XmlSerializer 생성자에 전달되는 Type이 포함된 Assembly 파일을 인자로 전달하면 되는데, 만약 위의 예제 코드에서 "MyClass" 타입이 포함된 Assembly 파일명이 "ClassLibrary1.dll"이라면 다음과 같이 실행해 줄 수 있습니다.

C:\XmlSerializerTest\bin\Debug>sgen ClassLibrary1.dll
Microsoft (R) Xml Serialization support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Serialization Assembly Name: ClassLibrary1.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
Generated serialization assembly for assembly C:\XmlSerializerTest\bin\Debug\classlibrary1.dll 
  --> 'C:\XmlSerializerTest\bin\Debug\ClassLibrary1.XmlSerializers.dll'.

C:\XmlSerializerTest\bin\Debug>

자, 이제 다시 한번 "F5" 키를 눌러서 디버깅 모드로 진입하면 이번에는 "first-chance exception"이 전혀 발생하지 않습니다.




끝으로 읽을 거리 하나 제시하고 마치겠습니다. ^^

Avoid UAC prompt in IE component 
; http://blogs.msdn.com/carloc/archive/2007/06/22/avoid-uac-prompt-in-ie-component.aspx
; https://www.cloudnotes.io/avoid-uac-prompt-in-ie-component/

비스타 환경에서의 스마트 클라이언트 구동에 있어서 XmlSerializer와 관련한 재미있는 문제들이 지적되고 있습니다.



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







[최초 등록일: ]
[최종 수정일: 12/15/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2008-02-23 05시33분
XmlSerializer 생성자의 실행 속도를 올리는 방법 - 두 번째 이야기
; http://www.sysnet.pe.kr/2/0/521
kevin25
2011-06-23 10시34분
Could not find the file 'C:\WINDOWS\TEMP\<XML serializer(Random generated file name)>.dll
; (broken) http://blogs.msdn.com/b/asiatech/archive/2010/08/02/could-not-find-the-file-c-windows-temp-lt-xml-serializer-random-generated-file-name-gt-dll.aspx

전혀 별개의 문제이긴 하지만, AllocConsole이 호출되는 경우에도 보안상의 이유로 발생할 수가 있군요. ^^
정성태

... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11837정성태3/6/201939839기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201923413오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921884.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920712개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921233개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917134오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916993오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916650오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918334개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926305개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919214오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919397오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924669개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919083오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920669오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201919085오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919853오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922874오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922141Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920212VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916541오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201920035Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918289오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917085오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918440.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915719오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...