The scenario with the thread should be explained in more detail: you have to use such an non-trivial tool as
System.Threading.Thread.Abort
:
http://msdn.microsoft.com/en-us/library/system.threading.thread.abort.aspx[
^].
In contrast to some common believe,
it does not terminate thread. It performs such a non-trivial operation as
exception seeding into the target thread. The exception is
System.Threading.ThreadAbortException
, you can handle it to perform some last clean-up action, the "last will" of the thread:
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx[
^].
In general case,
if can be dangerous. You should use such things only if you understand very well what you are doing. But: if the code is hanging, it may means that it is already bad enough, so you simply don't have a better remedy in this situation.
Now, about loading and unloading. This is a complex matter which I would advise not to get into, unless you have extremely good understanding of technology. The kind of DLL makes dramatic difference.
If this is a native (unmanaged) DLL, you normally use it via P/Invoke:
http://en.wikipedia.org/wiki/P/Invoke[
^],
http://msdn.microsoft.com/library/en-us/vcmxspec/html/vcmg_PlatformInvocationServices.asp[
^].
This CodeProject article could also be helpful:
http://www.codeproject.com/csharp/EssentialPInvoke.asp[
^].
If you invoke some methods in you DLL, you won't be able to load or unload it. (Again, you did not explain any reasons for doing it, so I would warn you against it.) If you really want to load and unload it, you would rather invoke Windows API methods and use them:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684175%28v=vs.85%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179%28v=vs.85%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683212%28v=vs.85%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx[
^].
Now, about a .NET assembly. Normally, you just reference and use it. But can you load or unload it. Surprise:
you are not allowed to unload a .NET assembly from memory, as it would be unsafe, not acceptable for memory-managed system — what if some code keeps access to some methods/properties of already unloaded code?
You can only unload the .NET assembly if it was loaded in
some separate Application Domain. In this case, what you could do is to unload the whole Application Domain. But how to use the assembly if it is in a separate Application Domain?
This is tricky.
If you want further detail, please see my past answers on this topic:
Create WPF Application that uses Reloadable Plugins...[
^],
AppDomain refuses to load an assembly[
^],
code generating using CodeDom[
^].
—SA