首先是问题:我可以在未标记为异步的函数中使用await吗?
现在的细节。我在阅读这篇文章Hololens- Captureing 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()不是异步的)
人们往往会忘记背后async
和背后的事物await
。
不,您不能使用不是这样 await
的方法,async
但是可以调用ContinueWith
返回的方法,Task
并提供仅在任务完成时才执行的显式延续:
class Example
{
public void Start()
{
getFolderPath()
.ContinueWith(t =>
{
Console.WriteLine("...");
});
}
async Task getFolderPath()
{
await Task.Delay(1000);
}
}
相当于
class Example
{
public async Task Start()
{
await getFolderPath();
Console.WriteLine("...");
}
async Task getFolderPath()
{
await Task.Delay(1000);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句