Is it necessary to dispose of the data set in the finally block

Possible duplicate:
Should I Dispose () DataSet and DataTable?

I use a three-tier architecture in my application, on Datalayer I just get a dataset

Dataset dset= new Dataset(); try { dset = SqlHelper.ExecuteDataset(Con, CommandType.StoredProcedure, "StoredProcedureName", arParms); } catch {} finally { Con.Close(); dset.Dispose() } 

Is there a performance advantage for hosting a dataset object?

+4
source share
2 answers

If an object implements IDisposable , you must get rid of it.

The best way to get rid of any object that implements IDisposable is to wrap the creation in a using statement:

 using(var dset = SqlHelper.ExecuteDataset(Con, CommandType.StoredProcedure, "StoredProcedureName", arParms)) { } 

The above example creates the correct delete pattern for the created object. Using this template is a good rule of thumb - if you do this all the time, the chances of you forgetting to get rid of something important are omitted.


As Tim Schmelter noted, I did not address the performance issue.

In the case of datasets, there will be no performance advantage since deletion in the constructor is suppressed as described in the answers to this SO question . At the same time, the overhead of calling dispose is minimal.

I suggest you check both approaches for your specific use case to see which one works best, and the advantages of using one parameter over another are minus.

+4
source

You should place and close connections / objects having the IDisposable interface, it is most profitable to use performance, since your program will use less resources and / or release them faster.

You can create a new helper function that takes action, so you don’t have to think about cleaning up every time you use a dataset:

  public static void UseDataSet(Action<Dataset> code) { ... Dataset dset= new Dataset(); try { dset = SqlHelper.ExecuteDataset(Con, CommandType.StoredProcedure, "StoredProcedureName", arParms); code(dset); } catch { } finally { Con.Close(); dset.Dispose() ; } } 

To use the function:

  Helper.UseDataSet( (dataset) => { //use data set here, it will be closed and disposed afterwards dataset.something }); 
0
source

All Articles