maui
maui copied to clipboard
PropertyChanged causes COMException (Catastrophic failure) when application is closing
Description
I have a timer that updates a property in a view model. When application is closing this sometimes throws an COMException:
System.Runtime.InteropServices.COMException: 'Catastrophic failure (0x8000FFFF (E_UNEXPECTED))'
The more frequent the timer is running, the more likely it is to get this error.
Full sample code: https://github.com/pekspro/MauiIssues/tree/PropertyChangedCausesCOMException
Steps to Reproduce
- Create a new MAUI app.
- Update MainPage.xaml:
<VerticalStackLayout Spacing="25" Padding="30">
<Label
Text="{Binding Counter}"
FontSize="32"
HorizontalOptions="Center" />
</VerticalStackLayout>
- Update MainPage.cs:
using System.ComponentModel;
namespace MauiIssues;
public partial class MainPage : ContentPage
{
public ViewModel Model { get; set; } = new ViewModel();
public MainPage()
{
InitializeComponent();
BindingContext = Model;
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int Counter { get; set; }
private System.Timers.Timer Timer = new();
public ViewModel()
{
Timer.Interval = 1;
Timer.Enabled = true;
Timer.Elapsed += (o, s) =>
{
Application.Current.Dispatcher.Dispatch(() =>
{
Counter = (Counter + 1) % 1000;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(Counter)));
});
};
}
}
Run the application in Windows, and then close it.
Version with bug
Release Candidate 2 (current)
Last version that worked well
Unknown/Other
Affected platforms
Windows, I was not able test on other platforms
Affected platform versions
Windows 10.0.17763.0
Did you find any workaround?
No response
Relevant log output
No response
This might happen if you are trying to update things on the app that is shut down. Do you still get errors if you stop the timer in OnSleep?
You could also try adding a timer to the dispatcher using the Dispatcher.StartTimer. This will prevent any errors because the dispatcher will stop itself.
Thanks @mattleibow, I have tried both of your suggestions and they both work.
However, since I'm just updating a property in a view model, I would expect this to work. I would understand if things went wrong if I directly updated a control. In my real-life application this will be a bit harder to solve, but I will give it a try.
Verified this issue with Visual Studio Enterprise 17.3.0 Preview 1.0 [32427.455.main]. Repro on Windows. Sample Project: 6715.zip
still an issue on windows with 17.3.0 Preview 2.0 [32509.345.main].
I've updated sample application to .NET 7. The same issue remains.
Verified this on Visual Studio Enterprise 17.6.0 Preview 5.0. Repro on Windows 11 with below Project: 6715.zip
When application is closing, VS throws an COMException:
