I've written a cmdlet in C# that acts as a wrapper for a heavy/long-running synchronous operation. The method (someone else' code) reports percentage progress during this long-running operation via event handlers, and I'd like to hook these up to powershell's standard WriteProgress method to get the pretty-printed progress bar. However, I'm getting the following error message:
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.
Here's my code:
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);
}
Anyone able to spot what I'm doing wrong?
Update: Looks like the event handler is being triggered from a different thread than ProcessRecord(). How can I get the information I need back into the same thread as ProcessRecord()?
op.ProgressChangedraised in the same thread asop.Execute()called?