Powershell Custom Cmdlet - Call WriteObject in Background Thread
-
16-06-2021 - |
Question
Calling the WriteObject Method from a background thread is not possible!
Is there a possibility, to invoke/dispatch this method in the main thread of the powershell (like in WPF)?
Code sample:
protected override void ProcessRecord()
{
base.ProcessRecord();
...
Service.StartReading(filter, list => { WriteObject(list, true); } );
}
EDIT:
Any solution, workaround or quick fix?
thx, Mathias
Solution
I found a solution, which solves my problem.
created a ConcurrentQueue
ConcurrentQueue<LogEntryInfoBase> logEntryQueue = new ConcurrentQueue<LogEntryInfoBase>();
start a background thread to enqueue items to the ConcurrentQueue
Task.Factory.StartNew(() => Service.StartReading( filter, EnqueueLogEntryInfoBases));
meanwhile, try to dequeue from this queue in the main thread
for ( ; ; ) { LogEntryInfoBase logEntry = null; logEntryQueue.TryDequeue(out logEntry); if (logEntry != null) { WriteObject(logEntry); } Thread.Sleep(100); }
From my point of view, this solution/fix is ugly, but it works for my current issue.
OTHER TIPS
I was stuck on pretty much the same issue. In my opinion we can improve the solution by adding a sleep in the infinite loop. Of course we will need to have a global reference to our main thread and the background thread will need to call interrupt as soon as an item is added in queue.