views:

642

answers:

3

I have a C# program that uses a class from another assembly, and this class calls an unmanaged DLL to do some processing. Here is a snippet:

public class Util
{
    const string dllName = "unmanaged.dll";
    [DllImport(dllName, EntryPoint = "ExFunc")]
    unsafe static extern bool ExFunc(StringBuilder path, uint field);

    public bool Func(string path, uint field)
    {
        return ExFunc(new StringBuilder(path), field);
    }

    ...
}

Util util = new Util();
bool val = util.Func("/path/to/something/", 1);

The problem I'm having is that if I call "Func" my main C# program will not unload. When I call Close() inside my main form the process will still be there if I look in Task Manager. If I remove the call to "Func" the program unloads fine. I have done some testing and the programs Main function definitely returns so I'm not sure what's going on here.

+2  A: 

It might dispatch a non background thread that is not letting go when your main application closes. Can't say for sure without seeing the code but that is what I would assume.

It's probably less then ideal, but if you need a workaround you could probably use:

System.Diagnostics.Process.GetCurrentProcess().Kill();

This will end your app at the process level and kill all threads that are spawned through the process.

Quintin Robinson
A: 

Do you have the source code to unmanaged.dll ? It must be doing something, either starting another thread and not exiting, or blocking in it's DllMain, etc.

Brannon
+2  A: 

It looks like your unmanaged library is spawning a thread for asynchronous processing.

Odds are it supports a cancel function of some sort; I suggest that you attempt to call that at program shutdown. If your program is just completing before the asynchronous call happens to complete, look for a "wait for completion" function and call that before returning from your "Func" method.

Randolpho