Search code examples
c#multithreadingasynchronoustimersystem.timers.timer

Threading in C# . Using timer, threads and calling shell with output everything at the same time


I have a dilemma reading a lot of documentation about timers, threads and calling async process (cmd files), can't figure which method and which combination are the best for my scenario.

My scenario:

  1. Console application with .NET Framework 4.6
  2. I've a dictionary that has (as a key) an int that prefigures a specific second.
  3. The process begin on second zero (0)
  4. I've to call one (or more) process (different every time, with process start) when the seconds elapsed from the begin (step 3) are identical to the key of the dictionary (in step 2). This must be in the same second, so all calls must be in a different thread (I assume)
  5. This process will take more than a second to complete, and I have an async call that handle an event to take the response.

What I've got so far:

I'm running a System.Thread.Timer every second with a sample handler that call a process if there is any value for that second as key.
But I can't figure which timer (Form, Timer, Thread) must I've to use in order to complain this in a better performance / way. I read about this but I think is a bit complex to understand it. This maybe, is my first question, a good implementation about this.

Also I called the process with Ohad Schneider answer from this: Is there any async equivalent of Process.Start?

But again, which combinatory of call async / or desync may I must use with the chosen kind of timer?


Solution

  • You could sort the dictionary by second. Then you know how many seconds to wait before every call. For example, if you have entries for 5, 9, 10, and 22, then you wait 5 seconds before starting the first process. After that, you wait 4 seconds before making the next call, and so on.

    This leads to some pretty simple code that isn't polling unnecessarily:

    // this starts at second 00
    foreach (var second in dict.OrderBy(d => d.Key))
    {
        var secondsToWait = second.Key - DateTime.Now.Seconds;
        if (secondsToWait > 0)
        {
            await Task.Delay(secondsToWait * 1000);
        }
        // start your process here
    }