本文翻译自:Synchronously waiting for an async operation, and why does Wait() freeze the program here
Preface : I'm looking for an explanation, not just a solution. 前言 :我在寻找一个解释,而不仅仅是一个解决方案。 I already know the solution. 我已经知道了解决方案。
Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), async and await, I'm still a bit confused about some of the finer details. 尽管花了几天时间研究有关基于任务的异步模式(TAP),异步和等待的MSDN文章,但我对某些更详细的信息仍然感到困惑。
I'm writing a logger for Windows Store Apps, and I want to support both asynchronous and synchronous logging. 我正在为Windows Store Apps编写记录器,并且希望同时支持异步和同步记录。 The asynchronous methods follow the TAP, the synchronous ones should hide all this, and look and work like ordinary methods. 异步方法遵循TAP,同步方法应该隐藏所有这些内容,并且外观和工作方式与普通方法类似。
This is the core method of asynchronous logging: 这是异步日志记录的核心方法:
private async Task WriteToLogAsync(string text)
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync("log.log",
CreationCollisionOption.OpenIfExists);
await FileIO.AppendTextAsync(file, text,
Windows.Storage.Streams.UnicodeEncoding.Utf8);
}
Now the corresponding synchronous method... 现在对应的同步方法...
Version 1 : 版本1 :
private void WriteToLog(string text)
{
Task task = WriteToLogAsync(text);
task.Wait();
}
This looks correct, but it does not work. 看起来正确,但是不起作用。 The whole program freezes forever. 整个程序永久冻结。
Version 2 : 版本2 :
Hmm.. Maybe the task was not started? 嗯..也许任务没有开始?