Powershell自定义Cmdlet - 在后台线程中调用WriteObject

时间:2012-06-25 06:13:27

标签: powershell cmdlets cmdlet

无法从后台线程调用WriteObject方法!

是否有可能在powershell的主线程中调用/分配此方法(如在WPF中)?

代码示例:

protected override void ProcessRecord()
{
    base.ProcessRecord();
    ...
    Service.StartReading(filter, list => { WriteObject(list, true); } );
}

修改 The error, which occured after calling the WriteObject method from the thread

任何解决方案,解决方法或快速解决方法?

THX, 的Mathias

2 个答案:

答案 0 :(得分:2)

我找到了解决方案,解决了我的问题。

  1. 创建了ConcurrentQueue

    ConcurrentQueue<LogEntryInfoBase> logEntryQueue = 
            new ConcurrentQueue<LogEntryInfoBase>();
    
  2. 启动后台线程,将项目排入ConcurrentQueue

    Task.Factory.StartNew(() => Service.StartReading(
            filter, EnqueueLogEntryInfoBases));
    
  3. 同时,尝试从主线程

    中的队列中出队
    for ( ; ; )
    {
        LogEntryInfoBase logEntry = null;
        logEntryQueue.TryDequeue(out logEntry);
        if (logEntry != null)
        {
            WriteObject(logEntry);
        }
        Thread.Sleep(100);
    }
    
  4. 从我的观点来看,这个解决方案/解决方案很难看,但它适用于我当前的问题。

答案 1 :(得分:0)

我被困在同样的问题上。在我看来,我们可以通过在无限循环中添加睡眠来改进解决方案。当然,我们需要对主线程进行全局引用,后台线程需要在队列中添加项目后立即调用中断。