Greg B
Greg B

Reputation: 14898

Is there a patterns for executing a sequence of time-outs?

I'm playing with an app that displays instructions to the user at intervals specified in data.

Example data might look like:

Title    Duration  
Step 1   00:00:10
Step 2   00:00:05
Step 3   00:00:05
Step 4   00:00:10

Given this data, the user should be show the text "Step 1", 10 seconds later "Step 2" and so on. I'm knee deep in Timers and I'm wondering if there's well-thought-out pattern for achieving this kind of thing. I'm working in .NET.

Upvotes: 2

Views: 141

Answers (2)

Tim Destan
Tim Destan

Reputation: 2028

If you're using .NET 4.5, you can always use async/await to avoid Timers and callbacks:

static class Program
{
    public class ActionWithDelay
    {
        public Action Work { get; set; }
        public TimeSpan DelayAfter { get; set; }
    }

    public static async Task Run(IEnumerable<ActionWithDelay> actions)
    {
        foreach (var action in actions)
        {
            action.Work();
            await Task.Delay(action.DelayAfter);
        }
    }

    static void Main()
    {
        var actions = new[]
        {
            new ActionWithDelay { Work = () => Console.WriteLine("Step 1"), DelayAfter = TimeSpan.FromSeconds(10) },
            new ActionWithDelay { Work = () => Console.WriteLine("Step 2"), DelayAfter = TimeSpan.FromSeconds(5) },
            new ActionWithDelay { Work = () => Console.WriteLine("Step 3"), DelayAfter = TimeSpan.FromSeconds(5) },
            new ActionWithDelay { Work = () => Console.WriteLine("Step 4"), DelayAfter = TimeSpan.FromSeconds(10) },
        };

        Run(actions).Wait();

        Console.WriteLine("Done");
        Console.Read();
    }
}

Naturally, substitute the print statements with whatever it is you actually want to do.

Upvotes: 3

jjrdk
jjrdk

Reputation: 1892

It sounds like you are looking for Observable.Interval from the Reactive Extensions Framework (Rx). Have a look at these samples - http://rxwiki.wikidot.com/101samples#toc28 and http://rxwiki.wikidot.com/101samples#toc31

Upvotes: 2

Related Questions