开发者

Can the same DLL data be shared by 2 different processes?

开发者 https://www.devze.com 2023-01-01 19:06 出处:网络
I have two different C# applications that are running at the same time. I would like both of them to be able to access the same \"instance\" of a DLL (also in C#).

I have two different C# applications that are running at the same time.

I would like both of them to be able to access the same "instance" of a DLL (also in C#).

The DLL holds some data that I'd like to return to whichever of the two applications is asking for it.

My DLL is thread-safe so I was hoping this would be possible but I'm not sure how.开发者_高级运维

Any help or advice would be much appreciated.


The process space will be different so, for example, global variables in the DLL will be specific to each separate process. It is possible that the code in memory will be shared (Windows typically uses reference counting to make that part more efficient).

If you are wanting to share information that is accessed in the DLL between the two processes, then it seems likely that it will be necessary to use some kind of IPC (interprocess communication) mechanism such as sockets, shared memory, pipes, etc.


A DLL has no instance, it is loaded in a host process. Reference the assembly in both applications and use its classes/methods.

If you want to avoid deploying the same assembly for both applications you could put it in the GAC.


It's possible. You could install the DLL in the GAC (requires strong named assemblies) in order for both applications to have easy access to it.

Or stick it in a folder and have both apps search that folder for the dll.

MSDN support article

<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="MyAssembly2"  culture="neutral" publicKeyToken="307041694a995978"/>
            <codeBase version="1.0.1524.23149" href="FILE://C:/Myassemblies/MyAssembly2.dll"/>
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>


I don't know if this can be done in C# but in C++ you can also use Shared Memory sections if the info to share is not too complicated. You would simply need to synchronize access to this ressource using for example a mutex

A good article on the subject : http://www.codeproject.com/KB/threads/SharedMemory_IPC_Threads.aspx

Have fun


If your DLL creates a named MemoryMappedFile (in memory or on disk) then the two applications can share the memory created by the DLL. Each application will have a different pointer to the shared memory but the memory will actually be shared. You have to use the same name for the shared memory and you're on your own as far being thread safe between processes. (Named semaphores or mutexes will work, CriticalSection will not.)

0

精彩评论

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