[英]How to wait for completion of asynchronous function c# winrt
I have code which gets the photo from a web camera. 我有代码从网络摄像头获取照片。 I need to write a mechanism that would be expected to complete this process. 我需要编写一个可以完成此过程的机制。 How do I do this? 我该怎么做呢? I have the following code: 我有以下代码:
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var memStream3 = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var mediaCaptureMgr1 = new MediaCapture();
await mediaCaptureMgr1.InitializeAsync();
mediaCaptureMgr1.SetPreviewMirroring(true);
await mediaCaptureMgr1.CapturePhotoToStreamAsync(imageProperties, memStream3);
await memStream3.FlushAsync();
memStream3.Seek(0);
WriteableBitmap wb1 = new WriteableBitmap(320, 240);
wb1.SetSource(memStream3);
//1
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(0.1));
//if CapturePhotoToStreamAsync finished? OR memStream3 not null?
//break;
}
//2
If I start to do anything with wb1 at //1, I will not work because wb1 = null. 如果我在// 1开始对wb1做任何事情,我将无法工作,因为wb1 = null。 If I start doing it at //2 the wb1! 如果我在// 2 wb1开始这样做! = null because I waited until all the async function are completed. = null因为我等到所有异步函数都完成了。
Instead of wb1.SetSource(memStream3);
而不是wb1.SetSource(memStream3);
you should call await wb1.SetSourceAsync(memStream3);
你应该调用await wb1.SetSourceAsync(memStream3);
and all should be good. 一切都应该是好的。 Otherwise you could set var wb1 = new WriteableBitmap(1, 1);
否则你可以设置var wb1 = new WriteableBitmap(1, 1);
and wait until wb1.PixelWidth
grows bigger than 1 when SetSource
is done, but this method with Task.Delay
polling is suboptimal. 等待,当SetSource
完成时, wb1.PixelWidth
大于1,但这个使用Task.Delay
轮询的方法不是最理想的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.