✅ I need some clarification regarding events and class communication.

Hi guys. I've got a class in a project which fires an event in a simple service I've created so it can be subscribed to inside another unrelated class. Here's the code: This is the method in the service which invokes the event handler. I inject this in to both the subscribing class and the one I intend to raise it.
public event EventHandler? OnKanbanCardOrderChanged;
public void NotifyKanbanCardOrderHasChanged()
{
EventHandler? handler = OnKanbanCardOrderChanged;
handler?.Invoke(this, EventArgs.Empty);
}
public event EventHandler? OnKanbanCardOrderChanged;
public void NotifyKanbanCardOrderHasChanged()
{
EventHandler? handler = OnKanbanCardOrderChanged;
handler?.Invoke(this, EventArgs.Empty);
}
This is the method in the class in which I activate the event:
async void OnCardDeleteConfirmed()
{
await _cardDetailsDialog.CloseDialog();
AppState.NotifyKanbanCardOrderHasChanged();
}
async void OnCardDeleteConfirmed()
{
await _cardDetailsDialog.CloseDialog();
AppState.NotifyKanbanCardOrderHasChanged();
}
This is in the class where I'm subscribing to the event:
protected override async Task OnInitializedAsync()
{
AppState.OnKanbanCardOrderChanged += KanbanCard_OnCardDeleted;
}

async void KanbanCard_OnCardDeleted(object? sender, EventArgs args)
{
Console.WriteLine("EVENT FIRED");
}
protected override async Task OnInitializedAsync()
{
AppState.OnKanbanCardOrderChanged += KanbanCard_OnCardDeleted;
}

async void KanbanCard_OnCardDeleted(object? sender, EventArgs args)
{
Console.WriteLine("EVENT FIRED");
}
Pretty standard and this works fine (I think). But whats the alternatives to this? I've been reading about the Mediator pattern, is that something which would be more fitting in this scenario? Thanks!
4 Replies
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
DannyRoastBeef㊙
DannyRoastBeef㊙OP4mo ago
Hi thanks for the reply. Yeah it's a Blazor server project. Sorry I should have mentioned that. My understanding was that it was okay to use async void for event handlers and nothing else. I'll stop using it, thanks for the tip. Yes I think I may have to restructure this. I assumed I'd be able to call code in an unrelated component using events but perhaps it's the wrong approach.
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
DannyRoastBeef㊙
DannyRoastBeef㊙OP4mo ago
Alright got it 🙂

Did you find this page helpful?