Need to beat the GC and have object destroyed once it goes out of scope

江枫思渺然 提交于 2019-12-05 14:15:36

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.

Eric Lippert

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.

n8wrl

Mutex implements IDisposable so wrap it in a using

using (Mutex m = new Mutex())
{
   //Use mutex here

}
//Mutex is out of scope and disposed

Use a try/finally block or use the IDisposable pattern and wrap your usage in a using statement.

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();
}


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
}

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.)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!