我知道这已被多次询问过,但我尝试了所有找到的解决方案,没有人适合我。
我有以下代码:
public async void setFile(QuickBrowseFile file) {
try {
LoggingDatabaseService db = new LoggingDatabaseService();
LoggingData data = await db.getLoggingData(file.Id);
db.close();
if (data != null) {
List<LoggingModel> loggingData = data.RowData;
int numRows = loggingData.Count;
Application.Current.Dispatcher.Invoke((Action)(delegate {
for (int i = 0; i < numRows; i++) {
LoggingModel m = loggingData[i];
treeView.Items.Add(m);//!!!!!!!!!!!!exception here
}
}));
}
} catch (Exception ex) {
Logger.error(ex);
}
}
我尝试了另一种解决方案,但问题是我有一个gif图像,它使用How do I get an animated gif to work in WPF?的解决方案显示了一些帧。
使用下面的代码不会抛出任何异常,但会在加载时阻止gif图像。
var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(() => {
LoggingDatabaseService db = new LoggingDatabaseService();
//Console.WriteLine(file.Id);
LoggingData data = db.getLoggingData(file.Id);
db.close();
if (data != null) {
List<LoggingModel> loggingData = data.RowData;
int numRows = loggingData.Count;
for (int i = 0; i < numRows; i++) {
treeView.Items.Add(loggingData[i]);
}
}
}, CancellationToken.None, TaskCreationOptions.None, uiContext);