0

For a simple example, let's say my event is something that hits the database.

SystemTimer Ticker = new SystemTimer() { Interval = TimeSpan.FromSeconds(5).TotalMilliseconds, AutoReset = true };
Ticker.Elapsed += HitTheDatabase;

and let's say HitTheDatabase is async void and leverages awaitability in ways like await connection.OpenAsync();. Will this have any benefit as opopsed to just making the method void and having it do connection.Open();?

My understanding is that the elapsed event

  • is a "fire and forget" (which is fine for my application's needs)
  • runs the event in a different thread than the previous time it was called, if

Is that correct? Or can someone explain it to met in terms of graphs?

Like if I have

Ticker.Interval = 1000; 
Ticket.Elapsed += Wait2Seconds;

and

private static void Wait2Seconds(object source, ElapsedEventArgs e)
{
     Thread.Sleep(2000);
}

is that like

Time     |  0:01   |    0:02    |   0:03   |    0:04   |
-----------------------------------------------------------
Thread 1 | |-------waiting------|
Thread 2 |         |-------waiting------|
Thread 3 |                       |-------waiting------|   
Thread 4 |                                 |-------waiting------|

and would it be any different in an async version using Task.Delay(1000)?

user7127000
  • 3,143
  • 6
  • 24
  • 41
  • `Delay` isn't that accurate comparing with `Timer` class, sometimes difference between requested time and real is up to 100 millisecinds, as there is some overload for `await` state machine. Also, if you have many tasks in your system, `await` will degrade more. – VMAtm Mar 24 '17 at 05:43
  • 1
    @VMAtm While there is some overhead to Task.Delay, 100 milliseconds seems very unlikely. Task.Delay just creates a timer, and completes the task once it ticks... – Kevin Gosse Mar 24 '17 at 07:44
  • @KevinGosse I've got that delay in some wrongly written code, with too many tasks created, maybe it's an exclusive case. – VMAtm Mar 24 '17 at 14:10
  • Are you talking about [System.Timers.Timer](https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx)? To my knowledge, there's nothing called `SystemTimer` – Jim Mischel Mar 24 '17 at 19:21

1 Answers1

0

The benefit is going to come from the naturally asynchronous nature of interacting with the database. If you write your code to hit the database synchronously your going to be blocking a thread while you wait for the database response. An asynchronous call will free up the thread your hitting the database on until it responds. This applies to anything that hits the database and not specifically to your timer. For some more information have a look here benefits of asyc Db access.

Community
  • 1
  • 1
JSteward
  • 6,833
  • 2
  • 21
  • 30