c# - 关于异步/任务的初学者

标签 c# asynchronous

看看这段代码:

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>, 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.

关于c# - 关于异步/任务的初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041914/

相关文章:

c# - 在安全处理异常时避免第一次机会异常消息

android import android-async-http-master 有错误

c# - 如何从已经异步的代码创建任务?

c# - 只解析部分xml

c# - MVC1000 使用 IHtmlHelper.Partial 可能会导致应用程序死锁。考虑使用 <partial> 标签助手或 IHtmlHelper.PartialAsync

c# - 作为静态或非静态类的存储库?

c# - Xamarin.iOS MKLaunchOptionsDirectionsModeKey

javascript - 当一系列 readFile 调用在 node.js 中完成时如何运行函数?

javascript - Node.js 异步 waterfall ()回调已被调用

c# - 异步/等待性能