locked
Shortening Async Code

    Question

  • I have an extension method that returns an array created from data in an XML file. The code is as follows:
    <Extension()> Public Function Load(players As PlayerData()) As PlayerData()
    	Try
    		Dim tempfiletask As Task(Of StorageFile) = ApplicationData.Current.LocalFolder.GetFileAsync("Players.xml").AsTask()
    		tempfiletask.Wait()
    		Dim readtexttask As Task(Of String) = FileIO.ReadTextAsync(tempfiletask.Result).AsTask()
    		readtexttask.Wait()
    		Return CType(New XmlSerializer(GetType(PlayerData()), New XmlRootAttribute("Players")).Deserialize(New StringReader(readtexttask.Result)), PlayerData())
    	Catch aggregateex As AggregateException
    		If TypeOf (aggregateex.InnerException) Is FileNotFoundException Then : Return {}
    		Else : Return {}
    		End If
    	End Try
    End Function

    As you can see, the code creates Tasks, calls their Wait() methods, and then uses their Result properties. This is 3 statements (create the task, execute the task, use the result) that I would think could be done in one statement. Is there any way to do this without creating all the extra Task variables and manually calling their Wait methods? The reason I am doing this is because I need to finish reading the files before returning from the method. Also, if there is a way to avoid needing to convert the operations to tasks it would be nice (I am only familiar with Tasks). Any help would be appreciated. Thanks.

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Saturday, August 23, 2014 12:37 AM

All replies

  • Given the constraints you list your code is pretty much what you would do.

    I suspect you'd be better off awaiting the functions and returning a task from Load so it can be awaited.

    Saturday, August 23, 2014 2:31 AM
    Owner