C#C
C#3y ago
D.Mentia

❔ Events vs Tasks

In what situation would you use an Event over a Task that might wrap the event? As an example:
    private Component dragItem;

    public void OnMousePressed(EventArgs e)
    {
        dragItem = getItem(e.Position);
    }
    
    public void OnMouseReleased(EventArgs e)
    {
        dragItem.Position = e.Position;
    }

vs
    public async void OnMousePressed(EventArgs e)
    {
        var dragItem = getItem(e.Position);
        var released = await MouseReleasedEvent();
        dragItem.Position = released.Position;
    }

The second implementation is (obviously, to me) cleaner and easier to understand, all the logic together and with its vars staying in scope, for the situations where a process relies on multiple events.

Are there any memory or performance concerns with doing it that way? Or other good reasons to not do that
(Assuming I am just wrapping a basic Event with a TaskCompletionSource that's handled somewhere else)
(And assuming I'm using async Events correctly, which I haven't really looked into how to do them without async voiding but I assume it's possible...)
Was this page helpful?