我正在尝试在我的 Windows 8 应用程序中加载保存的数据。所有方法都是异步的。当 await GetStoredActivitiesInFolder(groupFolder);
第二次在 for 循环中运行时,我得到一个错误,因为线程仍在处理第一个(我猜)。
错误(当我删除上面这行代码时错误消失了):
An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code
Additional information: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
我的代码:
public async void LoadActivities()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFolder activityFolder = await storageFolder.CreateFolderAsync(App.AppSettings.ActivityDirectory, CreationCollisionOption.OpenIfExists);
IReadOnlyList<StorageFolder> groupFolders = await activityFolder.GetFoldersAsync();
ObservableCollection<ActivityDataGroup> groups = new ObservableCollection<ActivityDataGroup>();
foreach (var groupFolder in groupFolders)
{
ActivityDataGroup group = new ActivityDataGroup();
group.GroupName = groupFolder.Name;
ICollection<ActivityViewModel> activities = await GetStoredActivitiesInFolder(groupFolder);
foreach (var activity in activities)
{
group.Items.Add(activity);
}
AllGroups.Add(group);
}
this.IsDataLoaded = true;
}
最佳答案
我认为您的 GetStoredActivitiesInFolder 有可能在非 UI 线程上返回,那么您可以修改它使其不返回,或者执行类似的操作以确保您在 UI 线程上更新 View 绑定(bind)项目,例如像那样:
await Dispatcher.RunAsync(
CoreDispatcherPriority.High,
() =>
{
AllGroups.Add(group);
};
关于c# - Windows 8 - 在 For 循环中异步等待时出现线程错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12713621/