Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to do event driven programming in C#.NET?
    text
    copied!<p>How do you make a event-driven program where the execution of the main flow is suspended whenever an event is raised and handled, until the event handler finishes?</p> <p>I created the following program</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace EventTest { class Program { static void Main(string[] args) { Timer t = new Timer(2000); t.Enabled = true; t.Elapsed += new ElapsedEventHandler(TimerHandler); for (int i = 0; i &lt; 10000; i++) { for (int j = 0; j &lt; 100000000; j++) ; Console.WriteLine(i); } } public static void TimerHandler(object source, EventArgs e) { Console.WriteLine("Event started"); for (int i = 0; i &lt; 5; i++) { for (int j = 0; j &lt; 100000000; j++) ; Console.WriteLine("Event "+i); } Console.WriteLine("Event finished"); } } } </code></pre> <p>The main method is supposed to print sequential numbers, and an event is fired every 2 seconds. During the event handling, the program is supposed to print "Event started", "Event 1" to "Event 5", then "Event Finished", then returns.</p> <p>I expected Main() flow to stop while TimerHandler() is called, however my output suggests that Main() and TimerHandler() both are run simultaneously</p> <pre><code>0 1 2 3 4 5 6 7 8 9 10 11 Event started 12 Event 0 13 Event 1 14 Event 2 15 Event 3 16 Event 4 Event finished 17 18 19 20 21 22 23 Event started 24 Event 0 25 Event 1 26 Event 2 27 Event 3 28 Event 4 Event finished 29 30 31 32 33 </code></pre> <p>Is it possible to make the Main() method to stop while the event is handled?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload