What's the difference between the two? If I do Mutex.Close()
instead of Mutex.Release()
when shutting down my app, what would be the side effect?
问题:
回答1:
ReleaseMutex is used to allow another thread to obtain the mutex. It should only be called if you have acquired the mutex (called WaitOne
and acquired it or acquired through the constructor). Important Note ReleaseMutex
will throw an exception if you have not acquired the mutex.
Close is used to clean up the resources that have been allocated by declaring the mutex object, whether you ever blocked on it or not, if you have acquired the mutex it will release it (equivalent to calling ReleaseMutex
. If you plan to lock on the mutex for the whole application (i.e. using this to ensure a single instance of your app), then I would wrap it in a using statement like the example in Joseph Albahari's threading guide (a must read). The link is to the second section, scroll down to the Mutex part to see the example.