views:

38

answers:

2

Suppose I have a .NET dll with class 'B' and function 'C'.

I then have a multithreaded .NET program that references the dll.

Each thread instances the class 'B' and calls the function 'C'. Upon instantiation the class 'B' allocates all of its own variables on the heap. These variables are used by the function 'C'.

Does this create a distinct instance of the class (i.e. is it safe to call function 'C' in each of the threads of the main program) or would I have to somehow dynamically load the DLL.

(In other words, does the .NET DLL behave like the Win32 LoadLibrary function (reference counting), where you have to give one dll different names and then load those, to create distinct instances.)

+1  A: 

In .Net, type resolution is based on the assembly name, not the binary name. Thus, even if you manage to get two copies of your dll in the process memory, the type definition of the class B will be the same, and will use the same static variables instances.

However, each of your threads could load the assembly in a separate appdomain, in which case each appdomain gets its own instance of the static variables. The drawback would be that your code will cross an appdomain boundary each time it calls into the method C.

Franci Penov
Thanks for the reply Franci. So if the dll class 'B' has public variable 'A', then all instances of the class will use variable 'A', not their own copy, is that correct?
Bob Jacobs
Only if that variable is marked as static.
Franci Penov
A: 

You may be looking for Thread Local Storage, use the ThreadStatic attributes on your fields if that is what you are after.

Ian Ringrose