从后台线程获取结果并连续更新到UI线程UWP

时间:2017-12-11 08:07:59

标签: c# multithreading uwp

我正在开发一个项目,必须从服务器获取框架并将其显示到UI。所以我用这种方法连续得到它。但整个方法都在UI线程上运行,所以它会阻止我的UI一点点。我们有没有办法让所有在不同线程上运行的方法都返回结果,以便在UI线程上更新下面三行代码。

注意:我试图用Dispatcher.RunAsync覆盖Task.Factory.StartNew和下面三行的所有方法,但没有运气。因为值返回为空。

//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);
    }
}

1 个答案:

答案 0 :(得分:1)

你可以处理的方法是在单独的线程中运行非IU逻辑,然后调用UI线程来更新它:

await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => {
// UI THREAD
 });