Can't get FlowExceptionsToTaskScheduler to work for error handling (with TaskScheduler.UnobservedTaskException)
Describe the bug
I'm trying to use the FlowExceptionsToTaskScheduler parameter on a :
[RelayCommand(FlowExceptionsToTaskScheduler = true)]
private async Task RefreshOrdersAsync()
{
throw new Exception();
}
and retrieve the exception using the following code in App.xml.cs or AppShell.xaml.cs or MauiProgram.cs (same result):
TaskScheduler.UnobservedTaskException += (sender, args) =>
{
Console.WriteLine("test");
};
But the event hasn't been triggered. I've seen that the GC has to collect the task for the event to be triggered.
My question is, how can the GC be triggered in this context? Is it predictable or random? And is it a good idea to use this mechanism to set up a centralized exception management system?
Thank you in advance.
Regression
No response
Steps to reproduce
1- Blank MAUI project with MVVM toolkit.
2- Create page with it's view model (that extend `ObservableObject`)
3- Create command with `RelayCommand` and set `FlowExceptionsToTaskScheduler ` to true, throw exception in the command.
4- Add event handler for `TaskScheduler.UnobservedTaskException` in App.xaml.cs
5- Trigger the command using button control in the view.
Expected behavior
The event TaskScheduler.UnobservedTaskException is triggered.
Screenshots
No response
IDE and version
Rider
IDE version
No response
Nuget packages
- [ ] CommunityToolkit.Common
- [ ] CommunityToolkit.Diagnostics
- [ ] CommunityToolkit.HighPerformance
- [X] CommunityToolkit.Mvvm (aka MVVM Toolkit)
Nuget package version(s)
8.2.1
Additional context
No response
Help us help you
Yes, but only if others can assist
I also happened to run into this today and came here to log the same thing. 😅
Would be good to have a better global exception handler even if it's considered a code smell to most, I like to set something up so a worst-case scenario at least something is logged.
If it helps, I think the debugger is interfering with this mechanism, I've managed to get it working with the debugger disabled.
The other thing to watch out for is not having an exception thrown in the UnobservedTaskException event, for example if you want to display an alert (via DisplayAlert) don't forget to call MainThread.BeginInvokeOnMainThread to make it work on the UI thread.
Otherwise, regarding the purpose of this mechanism, I suggest you read the following issue: https://github.com/CommunityToolkit/dotnet/issues/262