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!
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With