synclock and mutex

  • Thread starter Thread starter cj
  • Start date Start date
cj said:
I take it a mutex is like a synclock but visible outside the program?

Yea, that's a pretty good working definition.

There are some differences, but at the end of the day they're both
True/False flags for "Busy / Not Busy".

The Monitor (the thing that underlies the SyncLock) has some nice methods on
it like TryEnter and PulseAll that make it easy to use in some situtations.
It also has the handy VB keyword SyncLock that deals with the Try/Finally
semantics required to use a Monitor in an Exception safe way.

On the other hand, the Mutex is also a WaitHandle, and therefore works with
all of that infrastructure (WaitOne, WaitAll, WaitAny, etc), which makes it
easy to use in some situations. For example, you can register a WaitHandle
with the CLR threadpool, and get a callback when the WaitHandle is set.
There are some scenarios where this behavior is very handy.

Personally, I tend to use:
- Monitor (Synclock) for almost all of my locking.
- ManualResetEvents for almost all of my Waiting ("Is this done yet? Call me
back when it's done.")
- Mutex for ensuring an application is "single instance".
 
Thanks. I've used synclock to make sure multiple threads don't trample
on each other when they are using a common class to say increment a
counter (to keep track of how many threads/transactions are currently
being handled) or write a log file. I was using:

<STAThread()> Public Sub main(ByVal CmdArgs() As String)
Dim procArray() As System.Diagnostics.Process
procArray =
System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess.ProcessName)
If procArray.Length > 1 Then
Dim thisProcHandle As Int32
thisProcHandle =
System.Diagnostics.Process.GetCurrentProcess.MainWindowHandle.ToInt32
For Each proc As System.Diagnostics.Process In procArray
Try
If Not proc.MainWindowHandle.ToInt32 = thisProcHandle Then
If IsIconic(proc.MainWindowHandle) Then
ShowWindow(proc.MainWindowHandle, 9)
End If
SetForegroundWindow(proc.MainWindowHandle)
End If
Catch
End Try
Next
Exit Sub
End If
Dim mainForm As New Form1
Application.Run(mainForm)
End Sub

in vb2003 for single instance apps. VB2005 has that covered for what
I'm doing in the project properties.

Mutex just came up when I wanted to run 2 instances of an app and have
one know it was A and the other B. I'm counting on nobody starting a
3rd or it too would become B which really wouldn't cause much of a
problem. I just want to know which app processed what data and separate
logs.

Anyway, thanks for the info.
 
Back
Top