订阅EnvDTE80.DTE2.Events2.PublishEvents.OnPublishBegin的正确方法是什么?

时间:2015-09-15 18:59:23

标签: c# visual-studio envdte visual-studio-package

我正在将VS插件移植到VS包中。初始化包时,包会订阅OnBuildBegin和OnPublishBegin。 Visual Studio按预期触发OnBuildBegin,但从不调用OnPublishBegin。

或多或少相同的代码在Visual Studio 2013,2012和2010中作为插件工作。但在VS 2015中作为VS包,OnPublishBegin似乎没有功能。

示例代码如下。

测试运行调试器的代码,该调试器配置为在实验模式下启动VS的第二个实例。在第二个实例中,我打开了另一个解决方案并使用“发布向导”进行发布。

using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace MyPackage
{
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About
    [Guid(VSPackage.PackageGuidString)]
    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
    [ProvideAutoLoad(UIContextGuids80.SolutionBuilding)]
    public sealed class VSPackage : Package
    {
        public const string PackageGuidString = "a8ddf848-00ea-4e4e-b11a-65663a8a8021";

        private DTE2 application;
        public VSPackage()
        {
        }

        protected override void Initialize()
        {
            base.Initialize();
            this.application = (DTE2) this.GetService(typeof(DTE));

            ((Events2)this.application.Events).BuildEvents.OnBuildBegin += this.OnBuildBegin;
            ((Events2)this.application.Events).PublishEvents.OnPublishBegin += this.OnPublishBegin;
        }

        private void OnBuildBegin(vsBuildScope scope, vsBuildAction action)
        {
            MessageBox.Show("OnBuildBegin");
        }

        private void OnPublishBegin(ref bool pubContinue)
        {
            MessageBox.Show("OnPublishBegin");
        }
    }
}

任何人都可以为我解释这个问题吗?

1 个答案:

答案 0 :(得分:1)

强烈建议保留对Events对象的引用以保护它们免受GC的侵害:

protected override void Initialize()
{
    events = application.Events;
    buildEvents = events.BuildEvents;
    publishEvents = events.PublishEvents;
    buildEvents.OnBuildBegin += this.OnBuildBegin;
    publishEvents.OnPublishBegin += this.OnPublishBegin;
}

private Events2 events;
private BuildEvents buildEvents;
private PublishEvents publishEvents;