Jon Maximys
Jon Maximys

Reputation: 75

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.

Upvotes: 0

Views: 968

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

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.

Upvotes: 2

Related Questions