Search code examples
c#multithreadingdispose

What to do if i need a Disposable item the whole run?


What if i need a Disposable item the entire run of my application? There are some cases when this seems necessary, for example if i want to sync 2 threads with: System.Collections.Concurrent.BlockingCollection.

If then one Thread uses Using, and disposes of it, and the other Thread hasn´t been able to shut down or is waiting on BlockingCollection (you can set a timeout), it will then get a Disposed Exception.

And there are probably more cases when this is true, so is there a way to bypass this, or should i simply make the object on Initialization, and dispose of it on Close?

EDIT: Here is what Visual Studio tells me when i use a Disposable item.

First how i use it, in an example:

private void Initialize()
        {
            Queue = new System.Collections.Concurrent.BlockingCollection<byte[]>();
            Queue.Dispose();
        }

And i get this:

warning : CA2213 : Microsoft.Usage : 'Capture' contains field 'Capture.Queue' that is of IDisposable type: 'BlockingCollection<byte[]>'. Change the Dispose method on 'Capture' to call Dispose or Close on this field.

So that just get´s me confused. I have told it to dispose right after it has been made, and it still wants me to dispose of it:S

EDIT 2:

Is this the correct way of disposing object that are supposed to be alive the whole application run?

protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
        Queue.Dispose();
    }
    base.Dispose(disposing);
}

As you can see, i added Queue there.

This doesn´t seem right though, feels weird to work with the Designer.cs file and add stuff under components.Dispose();

But hopefully it´s correct.


Solution

  • The Form project item template gets programmers into trouble. They know that you're not supposed to edit the Designer.cs file. But it is not quite that straight-forward. Open the file and note the region:

        #region Windows Form Designer generated code
    

    That's the code you should not mess with. And note that the Disposing(bool) override is above this region. Which means that it is just fine to edit that one.

    Best thing to do is to simply cut/paste the Dispose() method from the Designer.cs file into the form's source code file. Now you have no trouble following the analyzer's advice:

        protected override void Dispose(bool disposing) {
            if (disposing) Queue.Dispose();
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }