Reputation: 1194
suppose i have an Array of Datatables, for for each Datatable in that Array i am going to start a Thread to do some processing.
class someclass()
{
private DataTable[] DataTableArray;
someclass(DataTable sometable)
{
//divide sometable and distribute them to DataTableArray
}
private void startThreads()
{
for (int i = 0; i < DataTableArray.Count(); i++)
{
Task.Factory.StartNew(() => Downloader(DataTableArray[i]));
}
DataTableArray = null; //is this line necessary?
}
}
in my startThreads()
Upvotes: 0
Views: 188
Reputation: 942040
Everybody is quick to dismiss this, but it is not actually entirely useless. Most code that sets an object to null gets optimized away by the jitter optimizer, not this one. Because it sets a field to null, not a local variable.
There are corner cases where dropping the reference to an array can pay off. Especially so when the array is large, more than 21250 elements. Setting the array reference to null allows it to be garbage collected early, earlier than would normally happen. Which is when the "someclass" object gets garbage collected.
Then again, in this specific case you'd better not have tens of thousands of elements in the array, that would put a lot of pressure on the threadpool. So ideally this would be a micro-optimization whose effect you'll never notice.
Upvotes: 1
Reputation: 2989
The .NET runtime will dispose of any objects no longer needed, you do not need to specify that an object is null. Nor do you need to call the Garbage Collector yourself unless in dire situations.
So the answer is no. That line is not necessary and in my opinion, not recommended.
Upvotes: 1