我正在为 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/