c# - 使用await时读取文本文件和代码跳转

标签 c# asynchronous async-await windows-8.1

我正在为 Windows 8.1 平板电脑编写一个应用程序,我正在尝试从我保存的文本文件中读取数据(该文本文件刚刚超过 1kb)。我的下面的代码在某些情况下可以工作,但主要会失败(调试/单步执行代码通常会看到它成功)。

StorageFolder folder = ApplicationData.Current.LocalFolder;
string fileName = "collections.json";
public Dictionary<string, string> masterDataObject;

private async void CallLoad()
{
   await this.Load();
}

public async Task<Dictionary<string, string>> Load()
{
    //create a file
    var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
    string fileContents = string.Empty;
    if (file != null)
    {
        //returns a JSON string
        fileContents = await FileIO.ReadTextAsync(file);//WHY DOES IT JUMP AT THIS LINE?????
    }
    Dictionary<string, string> customerFromJSON = JsonCrt.DeserializeObject<Dictionary<string, string>>(fileContents) ?? new Dictiy<string, string>();
    masterDataObject = customerFromJSON;
    return masterDataObject;
}

单步执行代码几次后,我可以看到该行 文件内容=等待...... 它退出该方法并继续执行不在我的 Load() 方法中的其余代码。

我已经回顾了 async 和 wait 并确实尝试理解它,但我的理解让我对为什么会发生这种情况感到困惑。

我相信等待意味着执行将停止,直到您从正在调用的代码中得到响应(显然不是)。

那么我应该如何使用异步使其正常工作,或者是否有比此代码更好的替代方案?

我已经看过并尝试了很多选择,但没有成功,任何建议将不胜感激。

最佳答案

it drops out of the method and continues with the rest of the code that is not in my Load() method

这正是它要做的,将控制权交给调用站点,直到异步操作完成。

我假设您的问题在于您的 CallLoad 方法是 async void 而不是 async Task,因此无法等待,这就是为什么您会看到它继续进行而无需等待内部异步 IO 完成。

I was under the belief that await meant that execution would stop until you get a response from the code you are calling

这仍然是完全正确的,如果您等待异步操作一直

So how should I be using async to make it work properly?

async void 仅适用于顶级事件处理程序。如果 CallLoad 不作为一个使用,它应该是 async Task 并等待:await CallLoad();

关于c# - 使用await时读取文本文件和代码跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29208446/

相关文章:

javascript - 我在异步函数中使用 Promise 是否正确?

c# - 使用泛型作为异步方法的返回类型

swift - 在 Swift 5.5 中编写同步和异步函数

javascript - 何时将函数标记为异步

c# - Enum<T>.Parse 允许解析任何整数字符串。这是 .net core 中的错误吗?

c# - 从C/C++到C#的参数类型转换: “double*”到 “out double”吗?

c# - Quickbooks SDK 13.0 ToDoAddRq C#

JQuery AJAX 请求行为同步

c# - 递归贝塞尔曲线算法在 C# 中不起作用

javascript - 在页面加载完成之前显示图像