我用C#编写了一个cmdlet,作为一个包装器来处理一个耗时的同步操作。此方法(别人的代码)通过事件处理程序在这个长时间运行的操作过程中报告百分比进度,并且我想将这些内容与Powershell的标准
WriteProgress
方法连接起来,以获取美观的进度条效果。然而,我收到以下错误消息:
The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread.
下面是我的代码:overrride void ProcessRecord()
{
LongRunningOperation op = new LongRunningOperation();
op.ProgressChanged += ProgressUpdate;
op.Execute();
op.ProgressChanged -= ProgressUpdate;
}
void ProgressUpdate(object sender, ProgressChangeEventArgs e)
{
ProgressRecord progress = new ProgressRecord(activityId: 1, activity: "Moving data", statusDescription: "Current operation");
progress.PercentComplete = e.ProgressPercentage;
WriteProgress(progress);
}
有谁能发现我错在哪里了吗?
更新:看起来事件处理程序被从与ProcessRecord()
不同的线程触发。我该如何将所需信息传回到与ProcessRecord()
相同的线程中呢?
op.ProgressChanged
是在调用op.Execute()
的同一线程中触发的吗? - user4003407