首页 > 解决方案 > VSTO: Event Handler failing to fire after a reboot

问题描述

I've come across a problem in my C# VSTO addin for Outlook.
There is an event handler registered at startup that updates a button on the ribbon of the main explorer Window when an item is selected. When deployed initially (by Clickonce) the addin works flawlessly. Changing selection updates the button each and every time.
Code for registering the event handler below:

Outlook.ExplorerEvents_10_SelectionChangeEventHandler selectionChangeEventHandler;

private void RegisterEvents(Outlook.Explorer Explorer)
{
    try
    {
        log.Debug("Registering Events");
        Application.Explorers.NewExplorer += Explorers_NewExplorer;
        selectionChangeEventHandler = new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(ThisAddIn_SelectionChange);
        Explorer.SelectionChange -= selectionChangeEventHandler;
        Explorer.SelectionChange += selectionChangeEventHandler;
        this.Application.OptionsPagesAdd -= Application_OptionsPagesAdd;
        this.Application.OptionsPagesAdd += Application_OptionsPagesAdd;
        Application.ItemSend -= Application_ItemSend;
        Application.ItemSend += Application_ItemSend;
        log.Debug("Events Registration Succeeded");
     }
     catch (Exception ex)
     {
         log.Debug("Event Registration Failed");
         log.Error(ex.Message);
         log.Error(ex.StackTrace);
     }
 }

 private void Explorers_NewExplorer(Outlook.Explorer Explorer)
 {
     RegisterEvents(Explorer);
 }

With the registration method being invoked like this

 RegisterEvents(Application.ActiveExplorer());

However after a reboot the event handler fires twice and then never fires again.

To attempt to track the issue down I added a line to start the debugger if a string is set in the app.config (as below)

if (String.Equals(ConfigurationManager.AppSettings.Get("attachDebugger"), "true", StringComparison.OrdinalIgnoreCase))
    Debugger.Launch();

After a reboot I can start Outlook and watch the plugin fail to update the selection. In then close Outlook, toggle the attachDebugger flag in the config and the button immediately starts working.

All other functionality in the addin works, so it's not a case that the addin is coming to a grinding halt.

I'm at a loss to know what to do next. If anyone has startling insight into why an event handler should run differently before and after a reboot (incidentally uninstalling and reinstalling the plugin causes it to work again for that session), I'd be very grateful. I'd also welcome anyones advice who can suggest methods for debugging an application when the problem fails to manifest under a debugger.

标签: c#event-handlingvstooutlook-addin

解决方案


您需要有一个全局(类)变量来存储指向 Explorer 对象的指针。否则它会被垃圾收集器释放。如果你不这样做,它只会在它被释放之前触发事件。


推荐阅读