所以在互斥體上使用訪問控制似乎是答案。下面是我做的:
在長期運行過程
Dim MutextWasCreated As Boolean
' Create a security rule for the mutex so other threads cannot take ownership
Dim MutexSec As New MutexSecurity
Dim rule As New MutexAccessRule(Environment.UserDomainName & "\" & Environment.UserName, MutexRights.TakeOwnership, AccessControlType.Deny)
MutexSec.AddAccessRule(rule)
App_Mutex = New Mutex(True, "Global\MyMutexName}", MutextWasCreated, MutexSec)
App_Mutex.WaitOne(-1, True)
然後,在客戶端應用程序,使用以下方法來嘗試打開互斥:從你的主要過程
Dim HostIsRunning As Boolean
Try
Mutex.OpenExisting("Global\MyMutexName", AccessControl.MutexRights.TakeOwnership)
Catch ex As Exception
If TypeOf ex Is UnauthorizedAccessException Then
' The mutex is created by the host to dissalow other threads from taking ownership. If we get this exception, we know the mutext has been created, thus the app is running.
HostIsRunning = True
ElseIf TypeOf ex Is WaitHandleCannotBeOpenedException Then
HostIsRunning = False
Else
Throw ex
End If
End Try
是的,你應該使用Mutex的。但前幾天我失敗了,所以我不會給出答案:) 此外,您可能需要全局互斥鎖,如MSDN中所述。 – leppie 2010-02-08 13:58:29
我在想同樣的事情,但最大的問題是,如果我使用Mutex.OpenExisting並定義了互斥鎖,則客戶端應用程序將獲得它的所有權,並在該線程結束時釋放,這不會起作用。這使我認爲使用互斥鎖並不一定是正確的方法。 – Jason 2010-02-08 14:04:03