0

I'm working with a class that manages a game's content and I'd like to know how I'm able to block calls to the dispose method without locking onto a shared dispose-lock? The worker methods themselves are thread-safe and can be executed in parallel, and that's why I don't want to lock those methods with a shared lock the dispose-method tries to acquire when it's fired.

public void DoSomething()
{
    lock (method1Lock) { /* ... */ }
}

public void Dispose()
{
    lock (method1Lock)
    lock (method2Lock)
    lock (methodXLock)
    {

    }
}

is not appropriate in this case as, as I previously mentioned, the methods (DoSomething in this case) can run in parallel.

Moritz Gunz
  • 702
  • 6
  • 15
  • 3
    What's the point of blocking in `.Dispose()`? Guess I'm not understanding *why* you need to block in here. *What* is running these things in parallel? That's the thing that should be blocking execution until methods are done running, vs. trying to enforce a runtime construct in this logic layer. – Joe Nov 30 '13 at 18:39
  • Something smelly is going on here. Are you passing on the ownership of these objects? He who created an instance should usually be responsible of disposing it. – Steven Nov 30 '13 at 18:55
  • Similar case: http://stackoverflow.com/questions/8927878/what-is-the-correct-way-of-adding-thread-safety-to-an-idisposable-object –  Nov 30 '13 at 19:03
  • @Steven Actually, it's not smelly at all. It's an asset loading class that loads and caches assets. The class itself will be passed around and used by multiple other instances on other threads while being disposed on the main thread **at the end of the app's lifetime**. But for a pain-free disposal I need to make sure Dispose won't be called while some thread is in the middle of a method. – Moritz Gunz Nov 30 '13 at 20:09

1 Answers1

0

Use a ReaderWriterLock. Let the Method... code take the read side and the Dispose the write side (which is exclusive).

usr
  • 168,620
  • 35
  • 240
  • 369
  • Thanks, this is the solution I've been looking for. – Moritz Gunz Nov 30 '13 at 20:21
  • Have you made sure that the methods actually gets scheduled before you dispose of the objects? Meaning, do you know that the object won't be disposed before one or more of the methods have a chance of being executed? – Lasse V. Karlsen Nov 30 '13 at 20:23
  • @LasseV.Karlsen No, I cannot _ensure_ calls to one of the methods. As mentioned, it's an asset loader which, though **very** unlikely, may not even be used at all. – Moritz Gunz Nov 30 '13 at 20:40