user1590636
user1590636

Reputation: 1194

Setting a variable to null when its no longer needed

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()

  1. after starting all threads can i set DataTableArray = null?
  2. i want to pass the Datatables by value, are they passed Default by value?, this is why i want to set it to null because that array is no longer needed

Upvotes: 0

Views: 188

Answers (2)

Hans Passant
Hans Passant

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

Patrick Magee
Patrick Magee

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

Related Questions