I'm using a library (ANet) which is written natively in C and I am interfacing with it using C# via a small subset wrapper dll which i've made in C and statically links to it. The library (ANet) has a DllMain which simply tracks the number of references to it (so "Process attach" and "Thread attach" counts) but it seems to go into the negative (i.e. more detaches than attaches).
Here's ANet's DllMain. It's quite simple:
BOOL WINAPI DllMain (HANDLE hModule, DWORD fdwReason, LPVOID lpReserved)
{
static int procRefCount = 0;
static int threadRefCount = 0;
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
procRefCount++;
break;
case DLL_PROCESS_DETACH:
procRefCount--;
break;
case DLL_THREAD_ATTACH:
threadRefCount++;
break;
case DLL_THREAD_DETACH:
threadRefCount--;
break;
}
if (procRefCount < 0) {
MessageBox( NULL, "Bug - negative processes?", "DP DLL Error", MB_OK|MB_ICONERROR );
return FALSE;
}
if (procRefCount > 1) {
MessageBox( NULL, "Bug - too many processes trying to use DP", "DP DLL Error", MB_OK|MB_ICONERROR );
return FALSE;
}
if (threadRefCount < 0) {
MessageBox( NULL, "Bug - negative threads?", "DP DLL Error", MB_OK|MB_ICONERROR );
return FALSE;
}
/* Only the first thread is allowed to join? */
if (threadRefCount > 0) {
//MessageBox( NULL, "Bug - too many threads trying to use DP", "DP DLL Error", MB_OK|MB_ICONERROR );
return FALSE;
}
return(TRUE);
}
.. Which i'm aiming to not change so I don't have to recompile and redistribute this prebuilt library.
So since C# seems to randomly create and destroy threads, DllMain is called sporadically throughout my program.
The thing is that the messagebox saying "Bug - negative threads?" will often also display!
Why would there be more THREAD_DETACH messages than THREAD_ATTACH messages?