I created a static class called "Delay" which basically accepts argument of (double delay, ThreadStart action). Here it is:
public class Delay
{
public static void Execute(double delay, ThreadStart action)
{
Delay.Execute((int)delay, action);
}
public static void Execute(int delay, ThreadStart action)
{
Timer t = new Timer(delay);
t.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
t.Stop();
action();
t.Dispose();
t = null;
});
t.Start();
}
private Timer t;
public Delay(int delay, ThreadStart action)
{
t = new Timer(delay);
t.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
if (t != null)
{
t.Stop();
action();
t.Dispose();
}
t = null;
});
}
public void Execute()
{
t.Start();
}
public void Cancel()
{
if (t != null)
{
t.Stop();
t.Dispose();
}
t = null;
}
}
I have a few questions.
- Is it really bad? My friend told me it'd give me errors for sure, but I haven't experienced any.
- Is there a way to improve it? It works fine now, but I don't want it to leak memory in the future.
Best regards.