Search code examples
vb.netasynchronousasync-awaitwin-universal-app

Returning list in async function in uwa vb.net


I am trying to parse through some xml files and return the results to a datagrid in UWA. The code builds fine but when running it returns

Unable to cast object of type 'System.Threading.Tasks.Task1[System.Collections.Generic.List1[Festplatten_Archiv_Client.Drive]]' to type 'System.Collections.IEnumerable'.

In my XAML.vb I am only calling the class to create the files and set the results as fileSource:

Public Sub New()
    InitializeComponent()
    dataGrid.ItemsSource = Drive.Drives
End Sub

Which works fine if I only add a sample Drive with

drivelist.Add(New Drive("Name",0, 0, 0), "location", "date"))

But as I want to parse through the XMLs, this is my code. This is my drives class:

 Public Shared Async Function Drives() As Task(Of List(Of Drive))
    Dim drivelist As New List(Of Drive)

    Dim folderpicked As StorageFolder
    Try
        folderpicked = Await StorageApplicationPermissions.FutureAccessList.GetItemAsync(ReadSetting("folderStorageToken"))
    Catch ex As Exception
        Debug.WriteLine("Fehler: " & ex.Message)
        folderpicked = Nothing
    End Try


    Dim xmlfiles As List(Of StorageFile) = Await folderpicked.GetFilesAsync()
    For Each file In xmlfiles
    ''Process files
    Next

    Return Await Task.Run(Function() drivelist)
End Function

It might be something with async programming, but I am very new to this. Thanks for any help!


Solution

  • You can make a blocking call to an Async routine from the ctor as follows:

    Dim drivesResult = Drives().GetAwaiter().GetResult()
    

    This is effectively forcing the routine to execute synchronously. If that's not what you want, then you'll need to explore a different alternative, e.g. the suggestion in the comments.