简体   繁体   中英

C# COM DLL is preventing VBA application from exiting

I have created a C# COM DLL which is essentially an enhanced progress bar that runs a System.Windows.Forms.Application.Run() on a new thread to show the form with the dialog. To use it in a third party application using VBA you do something like:

Set pg = CreateObject("MyNS.MyProgressBar")
pg.ShowBar()
.
.
pg.Progress = 0.5
.
.
pg.ShutDownBar()

The problem is that the user is able to close the application (using File->Quit, or similar) BEFORE pg.ShutDownBar() is reached. If the user does this, pg.ShutDownBar() is never called and the result is that although the window of the application is hidden, it still appears in task manager processes.

So my question is: Is there some way to detect whether the parent application has shut down and then abort the thread for the progress bar in c#?

I have tried System.Windows.Forms.Application.ThreadExit and System.Windows.Forms.ApplicationExit on the main thread that starts the dialog thread, but these events appear not to be raised when accessing the object through COM (though they are called when I create the object in .NET)....

Can anyone provide some advice?

This is problem with the way COM reference counting works. Unless the program calling into your COM wrapper releases the reference (as M. Babcock suggested that would require the program to get to a step where you do "set pg = Nothing"), your progress bar will not get properly shut down.

The only suggestion I can make is to setup a "timeout" property (and default it to say 30 seconds). Then use a background thread in the progress bar, that checks how long ago the last call to "pg.Progess" was made and if it's > timeout value, do a shutdown. This is assuming you can expect most VB scripts to report progress at least every X seconds (where X is the timeout value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM