简体   繁体   English

在Powershell Cmdlet中处理同步的最佳方法

[英]Best way to handle synchronization within Powershell Cmdlets

As an experiment, I have been writing a cmdlet in C# which makes use of a SystemFileWatcher. 作为实验,我一直在用C#编写一个cmdlet,它使用SystemFileWatcher。 As you know, the SystemFileWatcher will call a delegate when a changed event occurs. 如您所知,发生更改的事件时,SystemFileWatcher将调用委托。 I would like to send messages back to the user from the delegate. 我想将消息从委托发送回用户。 Specifically, I would like to call WriteProgress. 具体来说,我想打电话给WriteProgress。

Unfortunately, WriteProgress and, indeed, all other Write* methods will throw an exception if called from a thread other than the "pipeline thread". 不幸的是,如果从“管道线程”之外的线程调用WriteProgress,甚至所有其他Write *方法,都会抛出异常。 Further, Powershell doesn't seem to provide a SynchronizationContext, so I'm not sure how to marshal my delgates back to the correct thread. 此外,Powershell似乎没有提供SynchronizationContext,因此我不确定如何将代议任务编组回正确的线程。

It seems to me that, since Powershell requires GUI actions to execute on a particular thread, the framework should provide a way to marshal back to that thread. 在我看来,由于Powershell需要GUI操作才能在特定线程上执行,因此框架应该提供一种编组回到该线程的方法。 What am I missing? 我想念什么? Is there an easier way to synchronize threads in my cmdlets? 有没有更简单的方法来同步我的cmdlet中的线程? Is there a reason Powershell opted to use the ThreadPool based SynchronizationContext despite its Write* commands requiring the equivalent of a GUI thread? Powershell是否有理由选择使用基于ThreadPool的SynchronizationContext,尽管其Write *命令需要与GUI线程等效的原因?

Many thanks! 非常感谢!

I've had some luck in setting System.Management.Automation.Runspaces.Runspace.DefaultRunspace before my PS code runs. 在运行PS代码之前,我在设置System.Management.Automation.Runspaces.Runspace.DefaultRunspace方面有些运气。 (I did this for Powershell running as a WCF server). (我是针对作为WCF服务器运行的Powershell这样做的)。

Suggest you look at this blog , which shows setting the DefaultRunspace from C# before invoking a PS script, which is where I got the idea for my WCF server. 建议您看一下该博客 ,该博客显示了在调用PS脚本之前从C#设置DefaultRunspace的方法,这是我了解WCF服务器的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM