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

1 Answer 1

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); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.