Khi gỡ lỗi một ứng dụng sử dụng Semaphores để đồng bộ hóa chéo, tôi tình cờ sử dụng PowerShell để thay thế cho quá trình "khác". Làm một cái gì đó như thế này trong PowerShell hoạt động tốt:Tương tác bằng Mutexes (et al) trong 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()
Và tôi có thể gọi WaitOne()
và Release()
nhiều lần trên cùng một thể hiện của một Semaphore, thường xuyên như tôi cần.
Nhưng khi tôi cố gắng làm điều tương tự với một Mutex, PowerShell tiếp tục tuyên bố rằng các mutex bị bỏ rơi:
[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
Các lỗi có thể xảy ra bất cứ lúc nào tôi gọi WaitOne()
sau khi đã mua lại mutex một lần trước , hoặc là một WaitOne
gọi trước hoặc yêu cầu cho nó được ban đầu thuộc sở hữu trong constructor:
[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
là Powershell làm một số shenanigans chủ đề lạ trong nền hay tôi chỉ hoàn toàn quên cách Mutexes w ork?
+1 - Tôi chuẩn bị bình luận về v3.0, vì ví dụ của OP làm việc cho tôi trên 3.0 CTP, và tôi nhận ra v3.0 (console) là STA theo mặc định. Sau đó, thấy rằng bạn cũng đã làm điều đó :) – manojlds
+1 Xóa mẫu. Câu trả lời rõ ràng. –
Bạn không thể chỉ cung cấp tên mutex "toàn cầu", bất kể MTA/STA của cá thể Powershell là gì? – Signal15