Excel-DNA/IntelliSense

ExcelDNA Intellisense could lead to Excel hanging on exit

sharpe5 opened this issue · 3 comments

There appears to be a potential issue in this block of code that may prevent Excel from exiting properly:

public UIMonitor(SynchronizationContext syncContextMain)
{
    _syncContextMain = syncContextMain;

    // Make a separate thread and set to MTA, according to: https://msdn.microsoft.com/en-us/library/windows/desktop/ee671692%28v=vs.85%29.aspx
    // This thread was initially intended for UI Automation calls, particularly adding and removing event handlers.
    var threadAuto = new Thread(RunUIAutomation);
    threadAuto.SetApartmentState(ApartmentState.MTA);
    threadAuto.Start();
}

Recommending adding "threadAuto.IsBackground=true" before "threadAuto.Start()".

Without this line, if this thread does not exit automatically, then this will could prevent the entire process from exiting (i.e. Excel could hang on exit).

Note that ".IsBackground" has no effect on thread priority (this is a different property). All it means is that if the process exits, this thread will not block the process exiting. Unfortunately, this is set to false by default. The general rule is that this should always be set to true, unless it is absolutely imperative that the thread does some cleanup before the process exits.

Also suggest naming this thread (and all other threads in all projects related to ExcelDNA). I am running into issues with Excel hanging on exit, and the only possible plugins are Intellisense and another ExcelDNA plugin. If all the threads are named, I can check to see which thread was an issue by attaching a debugger. Perhaps something like:

threadAuto.Name="ExcelDNA.Intellisense.RunUIAutomation";

@sharpe5 It's years later, but I've finally done what you suggested here - thanks!