title: Why does DLL_THREAD_DETACH happen twice?
body: <p>I am learning COM. I wrote a simple COM component in the DLL and registered it in the registry. Then I created a simple client and tried to use my COM component. But I don't understand the <code>DllMain</code> behaviour (I read <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583%28v=vs.85%29.aspx" rel="nofollow noreferrer">this</a> also).</p>
  
  <pre><code>extern "C" BOOL WINAPI DllMain(
    _In_ HINSTANCE hinstDLL,
    _In_ DWORD     fdwReason,
    _In_ LPVOID    lpvReserved){
    pDll = hinstDLL;
    if (DLL_PROCESS_ATTACH == fdwReason){
      trace("DllMain(): DLL_PROCESS_ATTACH");
    }
    else if (DLL_THREAD_ATTACH == fdwReason){
      trace("DllMain(): DLL_THREAD_ATTACH");
    }
    else if (DLL_PROCESS_DETACH == fdwReason){
      trace("DllMain(): DLL_PROCESS_DETACH");
    }
    else if (DLL_THREAD_DETACH == fdwReason){
      trace("DllMain(): DLL_THREAD_DETACH");
    }
    else{
      trace("DllMain(): unknown variant...");
    }
    return TRUE;
  }
  </code></pre>
  
  <p>I expected for each <code>DLL_PROCESS_ATTACH</code> one <code>DLL_PROCESS_DETACH</code> to be called and for each <code>DLL_THREAD_ATTACH</code> one <code>DLL_THREAD_DETACH</code> to be called (if the exception doesn't happen).</p>
  
  <p>But I see for a single <code>DLL_PROCESS_ATTACH</code> there are two <code>DLL_THREAD_DETACH</code>:</p>
  
  <p><img src="https://i.stack.imgur.com/aoU7N.png" alt="enter image description here"></p>
  
  <p>Why does it happen?</p>