0

I am using System.Threading.Timer to make my current thread wait for a specific time. I am not using any intervals because I do not want the function to repeat itself. The problem with my code is that my timer does not work for due time values that are more than 2 seconds. Is it a memory issue or some error in my code. Can anyone help. Thanks. Here is my sample code.

   var timer = new System.Threading.Timer(a =>
                {
                   //Stuff to perform after 10 seconds

                }, null, 10000, 0);
Adnan Temur
  • 39
  • 1
  • 9

1 Answers1

4

You need to ensure that a reference to timer is being held somewhere, to prevent it from being garbage collected. For more information on this, see this post.

class DontGarbageCollect
{
    static System.Threading.Timer timer;

    public void ShowTimer() {
        // Store timer in this.timer to prevent garbage collection
        timer = new System.Threading.Timer(a =>
            {
               //Stuff to perform after 10 seconds

            }, null, 10000, 0);
    }
}
Adnan Temur
  • 39
  • 1
  • 9
Blue
  • 22,608
  • 7
  • 62
  • 92
  • Thanks that help me sort out the issue. Just a few edits were done in static timer to "static Timer timer" and this.timer to "timer". And the code worked fine. – Adnan Temur Feb 12 '19 at 00:23