在其他活动中取消订阅活动

问题描述 投票:0回答:1

在使用BackgroundWorker处理取消订阅事件时,我没有取消订阅事件。我可以在AsyncRunner中取消订阅,但不能在BackgroundWorker1_RunWorkerCompleted中取消订阅。

上下文:这是Autodesk Revit插件的一部分。我们想要在后台更新一些文件,但在我们这样做的时候,我们希望将命令捕获到受影响的部分并取消它。

我可以成功捕获命令并取消它,但是一旦BackgroundWorker结束,我就无法取消订阅。

任何时候都不会抛出异常。 编辑:它抛出一个“System.AccessViolationException HResult = 0x80004003 Message =尝试读取或写入受保护的内存。这通常表明其他内存已损坏.Source =无法评估异常源StackTrace:无法评估异常堆栈跟踪”主机程序退出。

using System.Threading;
using System.ComponentModel;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Events;

namespace RevitAsyncTest
{
    class Asyncer 
    {
        private static AddInCommandBinding Command { get; set; }

        internal static void AsyncRunner(UIControlledApplication app)
        {
            // Assign command and eventhand and subscribe to commandevents. 
            Command = app.CreateAddInCommandBinding(RevitCommandId.LookupCommandId("ID_VISUAL_PROGRAMMING_DYNAMO"));
            Command.BeforeExecuted += DynaExecuted;

            // Setup background worker 
            BackgroundWorker BackgroundWorker1 = new BackgroundWorker();
            BackgroundWorker1.DoWork += BackgroundWorker1_DoWork;
            BackgroundWorker1.RunWorkerCompleted += 
            BackgroundWorker1_RunWorkerCompleted;
            BackgroundWorker1.RunWorkerAsync();

            // I can un-subscribe here but this defeats the purpose
            Command.BeforeExecuted -= DynaExecuted;
        }

        private static void DynaExecuted(object sender, BeforeExecutedEventArgs e)
        {
            // Make user facing explanation
            e.Cancel = true;
        }

        private static void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Boilerplate code - replace later. 
            Thread.Sleep(30000);
        }

        private static void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {   
            // I can't un-subscribe here?!?!
            Command.BeforeExecuted -= DynaExecuted;
        }

    }
}

我是EventHandlers的新手,但我希望我可以在BackgroundWorker1_RunWorkerCompleted中从Command.BeforeExecuted取消订阅,但它仍然订阅。

c# .net events event-handling revit-api
1个回答
0
投票

对我而言,它看起来和听起来就像是在尝试进行交互而不是在有效的Revit API上下文中。如果你幸运的话,这是不允许的,会抛出这样的例外。如果最糟糕的情况发生,您可能根本看不到任何异常,只会破坏您的模型。灾难!

© www.soinside.com 2019 - 2024. All rights reserved.