Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner about async/Task

Have a look at this code:

private async void Lista()
{
    var _folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await _folder.GetFileAsync("thefile.txt");
    var read = await Windows.Storage.FileIO.ReadTextAsync(file);
}

Since the codeblock contais await i need to use async in the signature. This means that I cant simply add "Retrun read" at the end. (which is what i would like to get back from the method.)

From what I can understand i need to use task somehow. Any tips on how to retrieve the var read?

like image 798
Wranglerino Avatar asked Feb 11 '23 12:02

Wranglerino


2 Answers

You can change the returns type as Task<string>

private async Task<string> Lista()
{
     var _folder = Windows.Storage.ApplicationData.Current.LocalFolder;
     var file = await _folder.GetFileAsync("thefile.txt");
     var read = await Windows.Storage.FileIO.ReadTextAsync(file);
     return read;
}

From MSDN

An async method can have a return type of Task, Task<TResult>, or void. [...] You specify Task<TResult> as the return type of an async method if the return statement of the method specifies an operand of type TResult. You use Task if no meaningful value is returned when the method is completed. That is, a call to the method returns a Task, but when the Task is completed, any await expression that's awaiting the Task evaluates to void.

like image 157
Selman Genç Avatar answered Feb 15 '23 11:02

Selman Genç


You need to change your return type to Task of T where T is your intended return type, in this case string.

private async Task<string> Lista()
{
    var _folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await _folder.GetFileAsync("thefile.txt");
    var read = await Windows.Storage.FileIO.ReadTextAsync(file);
    return read;
}
like image 41
spender Avatar answered Feb 15 '23 09:02

spender