交互式使用互斥(等人)中是在調試使用信號量爲跨進程同步的應用程序,我偶然發現使用PowerShell來採取「其他」過程的地方的想法。做這樣的事情在PowerShell中正常工作:在Powershell的
// In C# application:
var sem = new Semaphore(0, 1, "CrossProcSem");
sem.WaitOne();
# In PowerShell session:
[1] C:\Projects $ $sem = New-Object System.Threading.Semaphore(0, 1, "CrossProcSem")
[2] C:\Projects $ $sem.Release()
而且我可以打電話WaitOne()
和Release()
反覆基於信號的同一實例,經常因爲我需要。
但是,當我試圖做同樣的事情用一個互斥量,PowerShell會聲稱互斥體被遺棄:
[1] C:\Projects $ $mtx = New-Object System.Threading.Mutex($false, "CrossProcMtx")
[2] C:\Projects $ $mtx.WaitOne()
True
[3] C:\Projects $ $mtx.ReleaseMutex()
[4] C:\Projects $ $mtx.WaitOne()
Exception calling "WaitOne" with "0" argument(s): "The wait completed due to an abandoned mutex."
At line:1 char:13
+ $mtx.WaitOne <<<<()
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DotNetMethodException
的錯誤似乎之前在已經獲取互斥一旦發生任何時間,我打電話WaitOne()
,無論是以前WaitOne
電話或要求它在構造函數中最初擁有:
[5] C:\Projects $ $mtx2 = New-Object System.Threading.Mutex($true)
[6] C:\Projects $ $mtx2.WaitOne()
Exception calling "WaitOne" with "0" argument(s): "The wait completed due to an abandoned mutex."
At line:1 char:14
+ $mtx2.WaitOne <<<<()
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DotNetMethodException
[7] C:\Projects $ $mtx3 = New-Object System.Threading.Mutex
[8] C:\Projects $ $mtx3.WaitOne()
True
[9] C:\Projects $ $mtx3.WaitOne()
Exception calling "WaitOne" with "0" argument(s): "The wait completed due to an abandoned mutex."
At line:1 char:14
+ $mtx3.WaitOne <<<<()
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DotNetMethodException
是PowerShell的做在後臺的一些奇怪的線程有心計或者我只是渾然如何互斥w ^掃?
+1 - 我談的是V3.0發表評論,因爲OP的榜樣爲我工作在3.0 CTP,我意識到V3.0(控制檯)爲STA默認。然後看到你做到了這一點:) – manojlds
+1清除樣品。明確的答案。 –
無論Powershell實例的MTA/STA如何,您都不能只提供一個「全局」互斥體名稱? – Signal15