4

I want to do something like this in C# (more specifically, WPF):

Thread.Invoke(MyCallback, 1000);

Which will just call MyCallback, 1 time, 1 second from now.

What is the easiest way to do this with .NET? Do I have to setup a Timer and hook an event?

1
  • Is it just me or has there been a flood of Timer-related questions lately?
    – Yuck
    Jun 9, 2011 at 15:02

6 Answers 6

6

You can use System.Timers.Timer to do this without spawning your own thread. Implement the Elapsed callback to do what you want, setting Enabled true and AutoReset false to achieve a single invocation.

Make sure you Dispose the Timer object once you are done with it!

4
  • I'd be interested in seeing code that wrapped this up as a method that took an action and delay. Jun 9, 2011 at 14:59
  • Sorry @George, I don't have such a canned wrapper to hand. Jun 9, 2011 at 15:04
  • @George I and at least one other answerer have posted possible implementations.
    – Jay
    Jun 9, 2011 at 16:43
  • @Jay, and they're much appreciated. I posted that comment when there were none. :) Jun 9, 2011 at 19:58
3

Here's a method that runs an Action after a certain timeout using a Timer:

static void Invoke(TimeSpan dueTime, Action action)
{
    Timer timer = null;
    timer = new Timer(_ => { timer.Dispose(); action(); });
    timer.Change(dueTime, TimeSpan.FromMilliseconds(-1));
}

I'm not sure how lightweight exactly a Timer is, but it should be better than blocking a ThreadPool thread.

Usage:

Invoke(TimeSpan.FromSeconds(5), () =>
{
    Console.WriteLine("Hello World");
});
2
Task.Factory.StartNew(() =>
{
    Thread.Sleep(1000);
    // Do Stuff
});

As noted in comments below, although easy to understand and short to write, this is a relatively inefficient/resource hungry way of doing this.

6
  • I don't think it's that bad, it won't really use many resources and the thread waiting won't use CPU time. I'd guess a timer would use more resources. Jun 9, 2011 at 14:50
  • 3
    I have a utility wrapper that uses System.Threading.Timer, but this is a reasonably clean way to do it. It blocks a thread-pool thread, as Kirk mentions, so you wouldn't want to use it if you are using this pattern in many places. In the worst case, you can starve the thread pool (especially if you have long delays) and your callbacks will execute much later than you expect.
    – Dan Bryant
    Jun 9, 2011 at 14:51
  • 3
    Even an idle thread uses 1MB of virtual memory by default; there's no point using a chunk of address space on doing nothing. And given that overall thread pool threads are limited, there's no point having a thread doing nothing for a second when it could be doing something else. Jun 9, 2011 at 14:54
  • @Dan, that's true, didn't think about the threadpool running out of threads etc. Does the Timer use windows messaging or something do avoid this kind of thing (using a thread)? Jun 9, 2011 at 14:54
  • Ok @Dan, @Tim, @Kirk. I stand corrected, my answer definately isn't the best way (will edit answer). Luckly OP asked for easiest way. :P Jun 9, 2011 at 14:56
0

Just my 2 cents,

public class WaitableWorker
    {
        private readonly System.Threading.Timer timer;
        public WaitableWorker(int interval, Action callback, bool blocking = false)
        {
            if (blocking)
            {
                Thread.Sleep(interval);
                callback();
            }
            else
            {
                timer = new System.Threading.Timer(_ =>
                                                       {
                                                           timer.Dispose();
                                                           callback();
                                                       },
                                                   null, interval, Timeout.Infinite);
            }
        }

    }

Usage

 WaitableWorker worker=new WaitableWorker(3000,DoWork);
0

Usage:

Delay.Invocation(MyCallback, 1000);

//or

Delay.Invocation(() => MyCallbackWithArgs(arg1, arg2), 1000);

Wrapper:

public class Delay
{
    readonly Timer _timer;
    readonly Action _action;

    private Delay(Action action, double delayMilliseconds)
    {
        _action = action;
        _timer = new Timer(delayMilliseconds);
        _timer.Elapsed += ExecuteCallback;
    }

    void ExecuteCallback(object sender, ElapsedEventArgs e)
    {
        _timer.Stop();
        _timer.Elapsed -= ExecuteCallback;
        _timer.Dispose();

        _action();
    }

    void Begin()
    {
        _timer.Start();
    }

    public static void Invocation(Action action, int delayMilliseconds)
    {
        var delay = new Delay(action, delayMilliseconds);
        delay.Begin();
    }
}
0

If you've got the Reactive Extensions, you can do this:

Observable.Return(true)
    .Delay(TimeSpan.FromSeconds(1))
    .Subscribe(_ => DoWork());

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.