0

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.

  1. Is it really bad? My friend told me it'd give me errors for sure, but I haven't experienced any.
  2. 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.

user3171969
  • 845
  • 1
  • 6
  • 4
  • 4
    SO is for specific problems. As it seems you don't have any problems (as your code seems to run fine for you), SO might be the wrong place. This looks more like a question for the folks at [codereview.stackexchange.com](http://codereview.stackexchange.com/). – KeyNone Jan 18 '14 at 17:15
  • http://stackoverflow.com/questions/620733/memory-leak-in-c-sharp – DayTimeCoder Jan 18 '14 at 17:16
  • @BastiM I concur with your opinion.. – DayTimeCoder Jan 18 '14 at 17:18

1 Answers1

4

You don't need any of this.Simply you can use async/await feature like:

public async Task Execute(double delay, ThreadStart action)
{
    await Task.Delay((int)delay).ContinueWith((x) => action());
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184