How does .NET effectively listen for raised events?

Does any event stream use event queue polling? Also, is this method different depending on the type of event? Some events are raised by the program itself, for example, by pressing a button, while others are raised externally, for example, the FileCreated event, which is read by FileSystemWatcher. Are these events handled differently under the hood?

+4
source share
3 answers

This is a very broad topic, I can only intelligently highlight the basics. The mechanisms are not specific to .NET, they apply to any program that runs on Windows. There are two main ways that an operating system or other program can trigger an event.

, , Click, , GUI. .NET - Application.Run(), . " ". -. winapi, , SendMessage() PostMessage(). .NET- , , , NativeWindow - . WndProc() . , .

-, , . FileSystemWatcher - , winapi, , - ReadDirectoryChangesW(). /, . , . . , , , .

winapi , .

+10

TL; DR:. ; . . .

, , ,.NET- , - ( ) .

, , (, string Name { get; set; }), " " ( ). ( ), ():

public event Action Completed
{
    add  // gets called for each `obj.Completed += value;`
    {
        if (completed == null)
        {
            completed = new Action(value);
        }
        else
        {
            completed += value;
        }
    }
    remove  // gets called for each `obj.Completed -= value;`
    {
        if (completed != null)
        {
            completed -= value;
        }
    }
}

private Action completed;  // backing field (a delegate) for the event

, — , . (Completed += …) (-=) add remove.

(Multi-cast) . += ( add) -= ( remove accessor). , += -= , ( add remove) (/ , Delegate.Combine Delegate.Remove).

; . , / , "backing-field"; — .

+6

. , , .

. , , , . , , . . , , string :

delegate string MyDelegate();

MyDelegate, , . , d, Do . :

class Program {

    delegate string MyDelegate();

    static string Do() {
        return "DO!";
    }

    static void Main() {
        MyDelegate d = new MyDelegate(Do);

        Console.WriteLine(d());     // Prints: DO!
    }
}

.NET Framework , , Action<...> Func<TResult, ...> .

, . , .

, :

event EventHandler Click;

EventHandler :

public delegate void EventHandler(Object sender, EventArgs e)

, , :

void HandleButtonClick(Object sender, EventArgs e) {
    // Do something!
}

When you register an event handler HandleButtonClickin an event Clickusing an operator +=, it adds a delegate that points to your function to the multicast event delegate.

this.Click += HandleButtonClick;

A multi-sheeted delegate is just like a regular delegate, but it can call several functions one after another in a specific order.

When you use this event, you are actually calling the delegate to call all of these functions:

this.Click();

And now you know how events work: delegates.

+3
source

All Articles