在使用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还是很陌生,但是我希望可以从Command.BeforeExecuted中取消订阅。BackgroundExecuted在BackgroundWorker1_RunWorkerCompleted中,但仍保持订阅状态。
答案 0 :(得分:0)
在我看来,这听起来像是您尝试在没有有效Revit API上下文的情况下进行交互。如果幸运的话,那是不允许的,并且会抛出这样的异常。如果情况变得更糟,您可能根本看不到任何异常,只会破坏模型。灾难!