看看这段代码:
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);
}
由于代码块包含await
,我需要在签名中使用async
。这意味着我不能简单地在末尾添加“Retrun read
”。 (这是我想从该方法中得到的结果。)
据我所知,我需要以某种方式使用任务。关于如何检索 var read
的任何提示?
最佳答案
您可以将返回类型更改为 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;
}
来自 MSDN
An async method can have a return type of
Task
,Task<TResult>
, orvoid
. [...] You specifyTask<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.
关于c# - 关于异步/任务的初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041914/