Windows 8 - Threading Error When Async Waits in For Loop


I'm trying to load saved data in my Windows 8 app. All methods are asynchronous. When 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).

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

Additional information: The application called an interface that was marshalled for a different thread. (Exception from 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)



        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, e.g. like that:

await Dispatcher.RunAsync(
    () =>