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: The error, which occured after calling the WriteObject method from the thread

Any solution, workaround or quick fix?

thx, Mathias

Was it helpful?

Solution

I found a solution, which solves my problem.

  1. created a ConcurrentQueue

    ConcurrentQueue<LogEntryInfoBase> logEntryQueue = 
            new ConcurrentQueue<LogEntryInfoBase>();
    
  2. start a background thread to enqueue items to the ConcurrentQueue

    Task.Factory.StartNew(() => Service.StartReading(
            filter, EnqueueLogEntryInfoBases));
    
  3. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top