问题描述
我想向我的 WPF 应用程序添加一个 AppStateService
以显示应用程序的状态以及当前在后台运行的所有内容。
你可以这样使用它
await appStateService.ExecuteWithStateAsync(new AppState("Loading order"),() => ...);
服务执行代码并将状态文本插入/删除到 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;
}
}
}
看起来很简单,但是当 deleteTimer.Elapsed 时出现错误“System.NotSupportedException”。 "Von diesem CollectionView-Typ werden keine Änderungen der "SourceCollection" unterstützt,wenn diese nicht von einem dispatcher-Thread aus erfolgen"
(此 CollectionView 类型不支持对 SourceCollection 的更改,除非它们是从调度程序线程进行的。)
但是为了避免这个问题,我使用 Currentdispatcher.Invoke
运行它。
我的思维错误在哪里?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)