0

I'm working on a project that has to get the frame from the server and display it to UI. So I used this method to get it continuously. But whole the method is running on UI thread so it blocks my UI a little bit. Do we have any way to make all the method that runs on the different thread and return the result to update three lines of code below on UI thread.

Note: I tried to cover all method of Task.Factory.StartNew and three lines below with Dispatcher.RunAsync but no luck. Because the value return is null.

//width = 1280, height = 960 
private async Task DisplayPreviewTwocamera_Camera1(int width, int height)
{
    _isPreviewing = true;
    try
    {
        byte[] buffer;
        SoftwareBitmap softwareBitmap;
        SoftwareBitmapSource _imageSource;
        while (true)
        {
            if (_isMinimize)
            {
                return;
            }
            buffer = await StreamServiceHandler.Instance.GetStreamCamera_First_1();
            if (buffer.Length == 0)
            {
                buffer = null;
                continue;
            }
            softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer.AsBuffer(), BitmapPixelFormat.Gray8, width, height);
            buffer = null;
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }
            //three lines of code below need to run in UI thread
            _imageSource = new SoftwareBitmapSource();
            await _imageSource.SetBitmapAsync(softwareBitmap);
            image_TwoCamera_Camera_1.Source = _imageSource;
        }
    }
    catch (Exception exception)
    {
        Debug.WriteLine(exception);
    }
}
Blacktempel
  • 3,935
  • 3
  • 29
  • 53
Bui Quang Huy
  • 1,784
  • 2
  • 17
  • 50

1 Answers1

1

The way you can deal with is running the non IU logic in separate thread and then call the UI thread to update it:

await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => {
// UI THREAD
 });
Ferus7
  • 707
  • 1
  • 10
  • 23