Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using statement usage in C#

Tags:

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!

like image 530
theOne Avatar asked Apr 25 '15 11:04

theOne


2 Answers

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.

like image 54
Yuval Itzchakov Avatar answered Sep 17 '22 10:09

Yuval Itzchakov


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.

like image 40
Ricardo Peres Avatar answered Sep 20 '22 10:09

Ricardo Peres