Skip to content

REQUESTS/EVENTS - Main Thread

Main Thread

Often when you publish an event, it can often be from a background thread or timer. As such, if you want to update your .NET MAUI, you need to be on the main thread. Transitioning on the main thread is not difficult, but you need an error trap to prevent your app from crashing out and you generally want to log those errors so you can fix them. This is where the [MainThread] attribute comes in.

There may also be cases where you want to ensure your request handler executes on the main thread as well. Maybe you want to display a dialog to a user to confirm an action or request permission to use some device hardware. Well… you need to be on the mainthread to do that for Android & iOS.

Event Handler Example

public class MyViewModel : BaseViewModel, IEventHandler<MyEvent>, IEventHandler<MyOtherEvent>
{
[MainThread]
public async Task Handle(MyEvent myEvent, CancellationToken cancellationToken)
{
// this will execute on the main thread, you are safe to update labels/collections/etc
}
public async Task Handle(MyOtherEvent myOtherEvent, CancellationToken cancellationToken)
{
// this event handle is not marked with [MainThread] so it will execute on the thread
}
}

Request Handler Sample

public class MyRequestHandler : IRequestHandler<MyRequest, MyResponse>
{
[MainThread]
public async Task<MyResponse> Handle(MyRequest request, CancellationToken cancellationToken)
{
// this will execute on the main thread, from here, you may want to
// * request a dialog
// * navigate somewhere using navigation service
// * request user permissions to use device hardware on mobile
}
}