-3

I have created an console application which i am scheduling in Task Scheduler as job. I have one class level Static variable in my application, below is the sample code. When my job runs for the first time, no issue. When i rerun the job immediately, I get "Object reference" error as I am setting it to NULL in finally block and doing "sb.clear()" in try block - static variable will be initialized only once.

Class Temp
{
   public static StringBuilder sb = new StringBuilder();
   try
   {
       sb.clear();
       ... some code
   }
   catch
   {}
   finally
   {
      sb = null
   }
}

My Task Scheduler job will run on every 24 hours. Since i set the variable to NULL, will this be Garbage collected after some time of first run? This way i wont run into "Object Reference" error when my job runs for second time after 24 hours (considering static variable will be created again).

I want to know what is the life time of static variable if i set this to NULL and if not i set this to NULL. Please clarify.

John Papa
  • 7
  • 3
  • 9
    If this object only exists to be used in the context of a particular method run once every so often then *it shouldn't be stored in a static variable*. It should be scoped to the specific operation that needs it. This prevents you from needing to know when you can and can't use a given variable, and creating bugs, like the one you apparently have, that involve using a variable when it isn't supposed to be. If you create it when you need it, and have that variable leave scope when the operation is done *you can't have bugs like that*. The GC is not your priority, working code is. – Servy Jan 30 '19 at 18:32

2 Answers2

0

The life time of a static varible is as long as your application is running. See more details here:

Scope and persistence Lifetime of data in variable static

I hope to this information be usefull

  • If i assign NULL to the variable, wont it be ready for garbage collection during GC cycle. Please advise. – John Papa Jan 31 '19 at 05:59
  • Variables are not subjects for the GC process - objects are. If you assign a NULL to the variable, then you simply remove a reference to an object which exists somewhere in the heap. That object will be collected by the GC only if it's not referenced anywhere else in the program. – Szab Jan 31 '19 at 10:28
-2

sb.clear(); //this cannot be used on a null stringBuilder In this case Finally sets your sb variable to null. So don't use Finally

Wilmar Arias
  • 186
  • 8
  • I know this, that is the issue. assigning NULL wont make it Garbage collected during GC cycle? Please advise. – John Papa Jan 31 '19 at 06:00