3

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

1
  • The standard System.Console.Out.WriteLine() method works great, but i need to pipe those result objects! Commented Jun 25, 2012 at 6:45

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

This answer should be a comment of the answer by SpecialHias, because it is not an answer to the OP's question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.