需要击败GC并有物体破坏,一旦超出范围 [英] Need to beat the GC and have object destroyed once it goes out of scope

查看:116
本文介绍了需要击败GC并有物体破坏,一旦超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码几个部分,我需要保护一个互斥。问题是,该代码看起来是这样的:

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

使用锁,它的作品,因为我想,但现在我需要使用互斥。这里最明显的问题是,如果我获得互斥体和富()或bar()的失败,我会抛出每个异常之前,明确地释放互斥锁。

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.

在C ++中,我将利用在堆栈上创建的对象的范围,并且将锁定在对象的构造互斥,然后在析构函数松开。随着.NET的垃圾收集,我不认为这会工作。我写了一个测试程序,并确认,如果我做这样的事情:

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.

推荐答案

为了提供作用域,可以让你的 AutoMutex 实施的IDisposable 并使用它是这样的:

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

在您的实现 IDisposable.Dispose的(),释放互斥锁。

In your implementation of IDisposable.Dispose(), release the mutex.

这篇关于需要击败GC并有物体破坏,一旦超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆