开发者

.NET DLLs and threads / distinct instances

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

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

Each thr开发者_JAVA百科ead 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.)


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜