theOne
theOne

Reputation: 357

using statement usage in C#

I have some doubts regarding the using statement:

I have a class called

MyJob which is Disposable. Then i also have a property on MyJob JobResults that is also Disposable.

MY code:

using (MyJob job = new MyJob())
{
    //do something. 
     FormatResults(job.JobResults)
}

public string FormatResuls(JobResuts results)
{
}

MY First question is: In this case after the using block are both MyJob and MyJob.Results disposed or only MyJob and NOT MyJob.Results?

I am also performing parallel processing w.r.t Tasks in C#:

Tasks allTasks = List<Tasks>

try
{
   foreach(Task t in allTasks)
   {
         // Each tasks makes use of an IDisposable object.
        t.Start();
   }
    Task.WaitAll(allTasks);
}
catch(AggregateExecption aex)
{
    /// How do I ensure that all IDisposables are disposed properly if     an exception happens in any of the tasks?
}

My second q, in the code above, what is the proper way to ensure to dispose off objects correctly when handling exceptions in tasks?

Sorry if my questions are too naive or confusing, as i am still trying to learn and understand C#. Thanks guys!

Upvotes: 8

Views: 697

Answers (4)

Ron Beyer
Ron Beyer

Reputation: 11273

There are a lot of good answers here but one thing remains. If you want to be assured that your object is properly disposed because it uses unmanaged resources, you should implement a destructor in your object, like:

class MyJob : IDisposable 
{
     private bool _disposed = false;
     protected virtual void Dispose(bool disposing)
     {
          if (!_disposed)
          {
              //Dispose unmanaged resources and any child disposables here
          }
     }

     void Dispose()
     {
          this.Dispose(true);
          GC.SuppressFinalize(this);
     }

     ~MyJob()
     {
          //ONLY use if you have unmanaged resources that DO NOT
          //implement their own finalizers.
          Dispose();
     }
}

However, it is recommended that you DO NOT use a finalizer (destructor) unless you are finalizing a type with unmanaged resources that does not include its own finalizer.

See https://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx for best practices on implementing IDisposable.

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

are both MyJob and MyJob.Results disposed or only MyJob and NOT MyJob.Results?

That is subjective to the implementation of your Dispose method. As we haven't seen it in your question, I'll assume that you aren't currently disposing your Result property in MyJob.Dispose, hence it will be the latter.

As only MyJob is wrapped in a using statement, and again assuming it does nothing to your Result property, it will be disposed as opposed to Results, which isn't wrapped in a using statement.

You could decide that MyJob, as it encapsulates your Result property, is responsible for the disposable of it as well. If you decide so, you can dispose Results in MyJobs.Dispose.

what is the proper way to ensure to dispose off objects correctly when handling exceptions in tasks?

If the delegate which is passed to the Task is wrapped in a using statement, you are safe, since using will transform your code to a try-finally block, if an exception occurs in your using block, the finally block will still run yourObject.Dispose.

Upvotes: 5

Ricardo Peres
Ricardo Peres

Reputation: 14525

Only MyJobs is disposed. For other properties, you need to understand object ownership: who owns the object should be responsible (in general) to dispose of it. A property implementing IDisposable could be used by other instances, so you can only dispose of it if you are the one who created it and there no other references to it, or the class fails gracefully if it knows that it has been disposed of.

Upvotes: 2

VladL
VladL

Reputation: 13033

1) The best way is to dispose JobResults inside of MyJob's Dispose() methode. Otherwise it's not disposed on it's own

2) I would implement the finally part, go through every object and dispose it. But in most cases you donät need to do that read this

Upvotes: 0

Related Questions