Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex.

Now I'm wondering whether it's ok to just call WaitOne() and ReleaseMutex() in a try-finally block or should I also dispose the Mutex (e.g. in a using block). If so I guess I should always catch the AbandonedMutexException on the WaitOne() method or am I wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
315 views
Welcome To Ask or Share your Answers For Others

1 Answer

A mutex is a Windows kernel object (here wrapped in a .NET object).

As such, it is an unmanaged resource that should be disposed.

More accurately, the .NET object contains a HANDLE to the mutex, which must be released/disposed of somehow.

I don't trust that code sample in the Mutex class docs where the mutex object is not disposed. Although Henzi has a good point in comment: The Mutex object is static and would be either disposed by the finalizer or destroyed by the Windows kernel when the process exits.

Also, note that Close() disposes the object as well.

Of course, there's nothing wrong with keeping an existing Mutex object in your app even while you don't use it. They are light resources.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...