How to do event-based programming in C # .NET?

How do you create an event-driven program where the execution of the main thread is suspended whenever an event occurs and is processed until the event handler completes?

I created the following program

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 < 10000; i++)
            {
                for (int j = 0; j < 100000000; j++) ;
                Console.WriteLine(i);
            }
        }
        public static void TimerHandler(object source, EventArgs e)
        {
            Console.WriteLine("Event started");
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 100000000; j++) ;
                Console.WriteLine("Event "+i);
            }
            Console.WriteLine("Event finished");
        }

    }
}

The main method is to print consecutive numbers, and the event fires every 2 seconds. During event processing, the program should print “Event Running,” “Event 1,” to “Event 5,” then “Event Complete,” and then return.

I expected the Main () thread to stop while TimerHandler () is being called, however my output suggests that the Main () and TimerHandler () functions start simultaneously

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

Is it possible to stop the Main () method during event processing?

+3
1

System.Timers.Timer, , .

, , .

, , Main , , .

, TimerHandler , Main, , :

namespace EventTest
{
    class Program
    {
        static object _Lock = new object();

        static void Main(string[] args)
        {
            Timer t = new Timer(2000);
            t.Enabled = true;
            t.Elapsed += new ElapsedEventHandler(TimerHandler);
            for (int i = 0; i < 10000; i++)
            {
                for (int j = 0; j < 100000000; j++) ;
                lock (_Lock)
                    Console.WriteLine(i);
            }
        }
        public static void TimerHandler(object source, EventArgs e)
        {
            lock (_Lock)
            {
                Console.WriteLine("Event started");
                for (int i = 0; i < 5; i++)
                {
                    for (int j = 0; j < 100000000; j++) ;
                    Console.WriteLine("Event "+i);
                }
                Console.WriteLine("Event finished");
            }
        }
    }
}
+3

Source: https://habr.com/ru/post/1753496/


All Articles