简体   繁体   中英

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. If I start doing it at //2 the wb1! = null because I waited until all the async function are completed.

Instead of wb1.SetSource(memStream3); you should call await wb1.SetSourceAsync(memStream3); and all should be good. Otherwise you could set 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM