[英]Windows 8 - Threading Error when async awaiting in For loop
I'm trying to load saved data in my Windows 8 app. 我正在尝试在Windows 8应用程序中加载保存的数据。 All methods are asynchronous.
所有方法都是异步的。 When
await GetStoredActivitiesInFolder(groupFolder);
await GetStoredActivitiesInFolder(groupFolder);
runs in the for loop for the second time I get an error because the thread is still processing the first one (I guess). 我第二次在for循环中运行,但出现错误,因为线程仍在处理第一个(我想)。
The error (it's gone when I remove the above line of code): 错误(删除上面的代码行后,错误消失了):
An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code
mscorlib.dll中发生类型'System.Runtime.InteropServices.COMException'的异常,但未在用户代码中处理
Additional information: The application called an interface that was marshalled for a different thread.
附加信息:该应用程序称为接口,该接口被编组用于其他线程。 (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
(来自HRESULT的异常:0x8001010E(RPC_E_WRONG_THREAD))
My code: 我的代码:
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;
}
I think it is possible your GetStoredActivitiesInFolder returns on a non-UI thread, then you could either modify it so it doesn't or do something like this to make sure you update the view-bound items on a UI thread, eg like that: 我认为您的GetStoredActivitiesInFolder可能在非UI线程上返回,那么您可以对其进行修改以使其不起作用,或者执行类似的操作以确保您更新UI线程上的视图绑定项,例如:
await Dispatcher.RunAsync(
CoreDispatcherPriority.High,
() =>
{
AllGroups.Add(group);
};
None of the above worked, but I randomly found it out. 以上都不起作用,但我随机发现了。 The LoadActivities function was called in the constructor of a page.
在页面的构造函数中调用了LoadActivities函数。 When I moved it to the OnLaunched method it magically worked.
当我将其移至OnLaunched方法时,它神奇地工作了。 I have no idea why but it did.
我不知道为什么,但是确实如此。 =)
=)
Anyway, thanks for the help, sorry to bother. 无论如何,感谢您的帮助,很抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.