I am using .dll reference to my application. i want to unload the .dll in a button click event. How to do it ???
You can't unload an individual assembly - you have to unload a whole AppDomain
. In other words, you'll need to load your other assembly (and associated code) in a new AppDomain
, then when you want to unload it you unload the AppDomain
.
Of course, this makes life a lot harder as you have to worry about marshalling calls between AppDomains - but it's all that .NET allows.
As Jon Skeet wrote, you cannot unload a DLL, but you can load the DLL in another AppDomain - and then unload the AppDomain. That is the only way to do it.
There are some things however that you need to be vary of, because you will naturally have to call functions across the AppDomain. This can happen in two different ways.
If you from one AppDomain (let's call it A), get a reference to an object that is instantiated in AppDomain B, then the default behaviour is that the object is serialized across the AppDomain boundary. That means that the object instance that A accesses is not the same instance that B accesses, and modifications made in A will not be reflected in B, unless you provide functionality to send to object back. This requires that the object is marked with Serializable.
You can however avoid the serialization by letting the class inherit from MarshalByRefObject. If the object is constructed in AppDomain B, and called from AppDomain A, the call will cross the AppDomain boundary. It will still be the same physical thread, so you don't have the overhead of a thread switch as you would in cross-process calls, or COM cross-apartment calls.
But if you construct an object in B that is referenced by an object in A, but the object in B is not accessed for 5 minutes, the object will be disposed. This behaviour can be overridden in MarshalByRefObject.InitializeLifetimeService().
See also the answer to Implementing .NET plug-ins without AppDomains. Note the discussion in the comments, where they point out that it very slowly leaks memory.