首先是问题: 我可以在没有标记为async的函数中使用await吗?
现在是细节。我正在阅读这篇文章 Hololens- Capturing Photo...,你可以看到作者发布了一些代码。 其中包括:
void Start ()
{
getFolderPath();
while (!haveFolderPath)
{
Debug.Log("Waiting for folder path...");
}
Debug.Log("About to call CreateAsync");
PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
Debug.Log("Called CreateAsync");
}
async void getFolderPath()
{
StorageLibrary myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
Windows.Storage.StorageFolder savePicturesFolder = myPictures.SaveFolder;
Debug.Log("savePicturesFolder.Path is " + savePicturesFolder.Path);
folderPath = savePicturesFolder.Path;
haveFolderPath = true;
}
现在注意一下,getFolderPath作为事件处理程序返回void, 但文档说这些方法不能被等待。作者通过使用while循环来进行等待。
但如果我这样做呢?
void Start ()
{
await getFolderPath();
Debug.Log("About to call CreateAsync");
PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
Debug.Log("Called CreateAsync");
}
//Notice how now it returns Task
async Task getFolderPath()
{
StorageLibrary myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
//.....
}
我可以这样做吗?(请注意,Start()不是异步的)
ContinueWith
是一个低级别、危险的 API。你可以(而且应该)使用await
代替它。 - Stephen Cleary