【发布时间】:2018-05-24 17:24:31
【问题描述】:
我正在处理一个必须从服务器获取框架并将其显示到 UI 的项目。所以我就用这个方法连续获取。但是整个方法都在 UI 线程上运行,所以它会稍微阻塞我的 UI。我们有没有办法让所有的方法在不同的线程上运行并返回结果来更新UI线程下面的三行代码。
注意:我试图用 Dispatcher.RunAsync 覆盖 Task.Factory.StartNew 的所有方法和下面的三行,但没有运气。因为返回的值是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);
}
}
【问题讨论】:
-
你能发布整个课程,或者你打电话给 DisplayPreviewTwocamera_Camera1 的拍子
-
我从 onNavigateTo() 方法调用它而不等待。我只是让它开火然后忘记了
-
那是阻塞线程的原因,如果你分享那部分,我可以提供一个例子。
标签: c# multithreading uwp