I want to add a AppStateService
to my WPF application to display the state of the app and all things that are currently running in the background.
You can use it like that
await appStateService.ExecuteWithStateAsync(new AppState("Loading order"), () => ...);
The services executes the code and inserts/deletes the state text to an ObservableCollection
public class AppStateService
{
public ObservableCollection<AppState> StateList { get; } = new();
public async Task ExecuteWithStateAsync(AppState state, Func<Task> code)
{
Dispatcher.CurrentDispatcher.Invoke(() => StateList.Add(state));
try
{
await code();
state.StateType = AppState.Type.Finished;
var deleteTimer = new System.Timers.Timer(2000);
deleteTimer.Elapsed += (source, e) => Dispatcher.CurrentDispatcher.Invoke(() => StateList.Remove(state));
deleteTimer.Start();
}
catch
{
Dispatcher.CurrentDispatcher.Invoke(() => StateList.Remove(state));
throw;
}
}
}
Looks quite simple, but I get an error "System.NotSupportedException" when deleteTimer.Elapsed. "Von diesem CollectionView-Typ werden keine Änderungen der "SourceCollection" unterstützt, wenn diese nicht von einem Dispatcher-Thread aus erfolgen"
(This CollectionView type does not support changes to the SourceCollection unless they are made from a dispatcher thread.)
But to avoid this problem is why I run it with CurrentDispatcher.Invoke
.
Where is my thinking error?