Unexpected release of named mutex



I have a mutex that releases while I am still holding a reference to
it! Maybe this is "garbage collection 101" and this old C++ programmer
just needs to get used to it...

Here's a boiled-down snippet of VB I used in order to implement a
single-instance app. (I can't use the application framework's single-
instance feature because it chokes on my form.)

Sub Main
Dim goodToGo As Boolean = False
Dim singleInstance As Threading.Mutex = Nothing
Try
singleInstance = New Threading.Mutex(True,
Application.ProductName & ".SingleInstance", goodToGo)
If Not goodToGo Then
' (find the existing instance and activate it)
End
End If
MainForm.ShowDialog()
Catch ex As Exception
' (log errors)
Finally
' doesn't work if you remove the next line
If goodToGo Then singleInstance.ReleaseMutex()
End Try
End Sub

This works, but if I take out the call to ReleaseMutex in the Finally
block I can them start as many instances as I want. The mutex releases
all by itself shortly after being acquired. This was highly
unexpected.

Silly me, thinking that I could keep a reference to an object by, uh,
keeping a reference to an object.

It appears that the garbage collector is outsmarting me by realizing
that the mutex object is never again being referenced and killing it.

I couldn't demonstrate this with a small test program. This is a
moderate sized app. A couple dozen forms, maybe two hundred source
files total.

(And yes, I know it's bad practice to not explicitly release a mutex
but one normally assumes that program exit cleans stuff like that up.)

Any other interpretations of what's going on here?

Thank you and be warned.
-- Carl
.



Relevant Pages

  • Re: [PATCH RFD] alternative kobject release wait mechanism
    ... There is no reason to hold reference to it. ... you grab the mutex excluding its removal and verified it's still there. ... It also wakes up all threads that are blocked trying to lock the ...
    (Linux-Kernel)
  • Re: WaitForSingleObject() will not deadlock
    ... You keep talking about needing to know the reference count. ... algorithm that uses a recursive mutex that cares in the slightest what the reference count ... attempts to lock appears to be isomorphic to a recursive lock, ... cycle detection until you reach the end of the list, ...
    (microsoft.public.vc.mfc)
  • Re: Library design for canceling a running operation?
    ... The main part of the public api is very similar to normal file I/O: ... cancel a running operation. ... thread that's performing the operation has a reference. ... The operation object contains a mutex, condition variable, and any ...
    (comp.programming.threads)
  • Re: [PATCH RFD] alternative kobject release wait mechanism
    ... Tejun Heo wrote: ... Here's an example where immediate-detach cannot be implemented. ... There is no reason to hold reference to it. ... I probably have over simplified it but using both mutex and reference ...
    (Linux-Kernel)

Loading