【发布时间】:2017-09-01 19:44:48
【问题描述】:
首先是问题: 我可以在未标记为 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() 不是异步的)
【问题讨论】:
标签: c# asynchronous