Reputation: 79
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);
Upvotes: 0
Views: 595
Reputation: 22911
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);
}
}
Upvotes: 4