可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have several sections of code that I need to protect with a Mutex. The problem is that the code looks something like this:
lock(mylockobject) {
if(!foo())
throw new MyException("foo failed");
if(!bar())
throw new MyException("bar failed");
}
Using lock, it works as I'd like, but now I need to use a mutex. The obvious problem here is that if I acquire the mutex and foo() or bar() fails, I would have to explicity release the mutex before throwing each exception.
In C++, I would take advantage of the scope of an object created on the stack, and would lock the mutex in the object's constructor, and then release it in the destructor. With .NET's garbage collection, I didn't think this would work. I wrote a test app and confirmed that if I do something like this:
public class AutoMutex
{
private Mutex _mutex;
public AutoMutex(Mutex mutex)
{
_mutex = mutex;
_mutex.WaitOne();
}
~AutoMutex()
{
_mutex.ReleaseMutex();
}
}
and then have code like this:
// some code here...
Mutex my_mutex = new Mutex(false, "MyMutex");
{ // scoping like I would do in C++
AutoMutex test = new AutoMutex(my_mutex);
test = null;
}
The destructor (finalizer?) doesn't get called until much later.
Google hasn't yet pointed me in the right direction, but I'm still working on it... Please let me know how you might solve this little problem, if it's even possible.
回答1:
In order to provide scoping, you can make your AutoMutex
implement IDisposable
and use it like this:
using(new AutoMutex(.....))
{
if(!foo())
throw new MyException("foo failed");
if(!bar())
throw new MyException("bar failed");
}
In your implementation of IDisposable.Dispose()
, release the mutex.
回答2:
Couple points.
1) The thing you want to search for is "the disposable pattern". Be very careful to implement it correctly. Of course, Mutex already implements the disposable pattern, so its not clear to me why you'd want to make your own, but still, it's good to learn about.
See this question for some additional thoughts on whether it is wise to use the disposable pattern as though it were RAII:
Is it abusive to use IDisposable and "using" as a means for getting "scoped behavior" for exception safety?
2) Try-finally also has the semantics you want. Of course a "using" block is just a syntactic sugar for try-finally.
3) Are you sure you want to release the mutex when something throws? Are you sure you want to throw inside a protected region?
This is a bad code smell for the following reason.
Why do you have a mutex in the first place? Usually because the pattern goes like this:
- state is consistent but stale
- lock access to the state
- make the state inconsistent
- make the state consistent
- unlock access to the state
- state is now consistent and fresh
Consider what happens when you throw an exception before "make the state consistent". You unlock access to the state, which is now inconsistent and stale.
It might be a better idea to keep the lock. Yes, that means risking deadlocks, but at least your program isn't operating on garbage, stale, inconsistent state.
It is a horrid, horrid thing to throw an exception from inside a lock-protected region and you should avoid doing so whenever possible. An exception thrown from inside a lock makes you have to choose between two awful things: either you get deadlocks, or you get crazy crashes and unreproducible behaviour when your program manipulates inconsistent state.
The pattern you really ought to be implementing is:
- state is consistent but stale
- lock access to the state
- make the state inconsistent
- make the state consistent
- if an exception occurs, roll back to the stale, consistent state
- unlock access to the state
- state is now consistent and, if there was no exception, fresh
That's the much safer alternative, but writing code that does transactions like that is tough. No one said multithreading was easy.
回答3:
Mutex implements IDisposable so wrap it in a using
using (Mutex m = new Mutex())
{
//Use mutex here
}
//Mutex is out of scope and disposed
回答4:
Use a try/finally block or use the IDisposable pattern and wrap your usage in a using statement.
回答5:
I think everyone has you covered with dispose/using, but here's an example using try/finally:
Mutex m = new Mutex()
m.WaitOne();
try
{
if(..)
throw new Exception();
}
finally
{
// code in the finally will run regardless of whether and exception is thrown.
m.ReleaseMutex();
}
回答6:
The GC isn't deterministic. Also, it behaves differently in debug mode, making this a bit more confusing to deal with in a development environment.
To create and use your auto mutex in the way you wish, implement IDisposable and use the using
keyword to destroy/release your AutoMutex when it goes out of scope.
public class AutoMutex : IDisposable
{
private Mutex _mutex;
public AutoMutex(Mutex mutex)
{
_mutex = mutex;
_mutex.WaitOne();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
// method may be called more than once from different threads
// you should avoid exceptions in the Dispose method
var victim = _mutex;
_mutex = null;
if(victim != null)
{
victim.ReleaseMutex();
victim.Dispose();
}
if(disposing)
{
// release managed resources here
}
}
}
and in use
using(new AutoMutex(new Mutex(false, "MyMutex")))
{
// whatever within the scope of the mutex here
}
回答7:
Why don't you surround the code in Foo() in a try-catch-finally, then have the finally release the mutex? (The catch can rethrow any exceptions, wrapping them in your custom exception type if desired.)
回答8:
For scope-based action, the C# idiom is try...finally
. It would look like this:
try {
acquire the mutex
do your stuff which may fail with an exception
} finally {
release the mutex
}
Using object instances for resource acquisition is a C++-ism which comes from the ability of C++ to handle instances with a life limited by the current scope. In languages where instances are allocated in a heap and destroyed asynchronously by a garbage collector (C#, Java), destructors (aka finalizers) are not the right tool for that. Instead, the finally
construct is used to perform scope-based action.