-4

I've a dilemma reading a lot of documentation about timers, threadings and calling async process (cmd files), can't figure wich method and wich 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 proccess 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've 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 wich 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 choosen kind of timer?

I'm a little lost here, sorry for my english and any comment, answer or suggest or edition to this post will be preciated. Thanks for your patience

Leandro Bardelli
  • 8,566
  • 13
  • 69
  • 102
  • Just a quick one - a "dilemma" is a choice between two equal options (can both be either good or bad options) and you can't choose between them. It is not a synonym for "problem". – Enigmativity Sep 14 '17 at 02:43

2 Answers2

2

I would use System.Diagnostics.Stopwatch as your timer. You can start it, pull the Elapsed seconds, and check to see if it is currently running.

Somthing like:

var s = new System.Diagnostics.Stopwatch();
s.Start();

while(true)
{
    await Task.Delay(500);
    var secondsElapsed = s.ElapsedMilliseconds / 1000;
    await Task.Run(() => Process.Start(processes[secondsElapsed]));
 }

 s.Stop();
Kevin Hirst
  • 846
  • 8
  • 16
2

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
}
Jim Mischel
  • 126,196
  • 18
  • 182
  • 330