2

I am creating a class, say LockHolder, to simplify the lock requiring logic. It implements the IDisposable interface, thus I can use it like this:

using(LockHolderCreater.Create(lockObject, waittime))
{
    //do something
}

The Dispose method of LockHolder releases lockObject (through Monitor.Exit) if it has been gained (through Monitor.TryEnter). That works fine if I create a new LockHolder object everytime LockHolderCreater.Create is called, but that would create too many instances of LockHolder. So I Write LockHolderCreater to maintain a list of LockHolder objects in order to reuse them. Now I am facing too problems:

First, when debugging, I found there are many such message as "A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll" in the output window. If what the "using" statement do is just to call the Dispose method, can I prevent this kind of exception?

Second, and more importantly, if I reuse the LockerHolder instances, at some early time after my application starts, a SynchronizationLockException exception would be thrown when I try to release a lock in the Dispose method, saying that "Object synchronization method was called from an unsynchronized block of code.". I checked my logic, but I don't think it is possible that one LockHolder instance would be used by two threads at the same time. Can this be related with the ObjectDisposedException noted above?

ABOUT the answer

I don't get a direct answer of my question, but Marc Gravell's answer has made it less neccessary.

3
  • Why would it create too many instances? There is a multi-million dollar beast called Garbage collector, why would you need to write your own reuse logic instead? Do you have special requirements?
    – nvoigt
    Nov 5, 2013 at 11:36
  • @nvoigt I am not sure whether I should trust the Garbage collector, I remembered a time when my application creates many socket connections (thus byte[] buffer), and until I decreased the buffer size, the memory just increases too fast. The maximum connections count are not too mush, just several hundreads, but some could be droped and new created. To solve that problem ,we implement another buffer of the byte[] buffer for reuse, and decreased the byte[] buffer size Nov 5, 2013 at 11:40
  • You can avoid the allocation problem completely here - see my edit Nov 5, 2013 at 11:47

3 Answers 3

4

Should you do it: probably not, except for very exceptional scenarios where you are in complete control of the types.

Can you do it: this depends entirely on the implementation - and you certainly wouldn't want to apply that at random to arbitrary types. If, however, the type is (as part of cleanup) returned to some pool and re-initialized and re-used, then yes it will work. But: you risk problems if the // do something code leaked the reference somewhere.

can I prevent this kind of exception?

yes: don't access an object after you've disposed it

saying that "Object synchronization method was called from an unsynchronized block of code."

I wonder - are you perhaps using await here? or an iterator block? or something like that? If the enter and exit code runs on different threads, it will fail.

If your intent here is to minimize allocations of LockerHolder, there is a better approach: use a struct:

using System;

struct Foo : IDisposable
{
    public Foo(string msg)
    {
        Console.WriteLine("Init: " + msg);
    }
    public void Dispose()
    {
        Console.WriteLine("Disposed");
    }

}

static class Program
{
    static void Main()
    {
        Console.WriteLine("Before");
        using (new Foo("Hi"))
        {
            Console.WriteLine("Do stuff");
        }
        Console.WriteLine("After");
    }
}

The Main method here compiles the Dispose using constrained-call, which means it doesn't box.

Note that for this to work, the LockHolderCreater.Create method must return the struct itself - it cannot return just IDisposable.

7
  • So you mean there is no way to reuse the Foo/LockHolder instances whatsoever, and that make my second question meaningless? Nov 5, 2013 at 11:50
  • And, why struct can minimize allocations than classes Nov 5, 2013 at 11:51
  • @RussellYan a struct is a value-type; a new Foo(...) here is not an allocation at all Nov 5, 2013 at 11:54
  • @RussellYan I explicitly said that it was technically possible to reuse the instances (as long as you control the types), but that it was not adviseable to do so. Or, indeed, necessary. Nov 5, 2013 at 11:55
  • Your suggestion about the use of struct can do the work. But for curiosity, I am wondering how I can reuse the disposable instances, without the ObjectDisposedException being thrown. And yes, I control the types Nov 5, 2013 at 12:02
1

It is a bad idea to abuse the using statement. It is not intended as a general-purpose "automatic undo". It is only intended as a means to ensure the disposal of unmanaged resources like database connections.

0

Declaring the variable inside the using statement's control expression limits the scope of the variable to inside the using statement.

Check this answer

1
  • 5
    Although not wrong, I don't think this answers the question in any way.
    – nvoigt
    Nov 5, 2013 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.