简体   繁体   English

使用MemoryStream后C#WPF UI冻结

[英]c# WPF UI freeze after using MemoryStream

I have some trouble with this code: 我在此代码上遇到了一些麻烦:

private Bitmap WriteableBitmapToBitmap(WriteableBitmap wb)
{
     BitmapEncoder encoder = new BmpBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(wb));
     using (MemoryStream ms = new MemoryStream())
     {
         encoder.Save(ms);
         Bitmap b = new Bitmap(ms);
         return b;
      }
}

If I start this code, the WPF UI freezes. 如果我启动此代码,则WPF UI会冻结。 I only want to convert a WriteableBitmap to a Bitmap so that I can use it for Emgu picture processing. 我只想将WriteableBitmap转换为Bitmap,以便可以将其用于Emgu图片处理。 The WriteableBitmap is created from Depthdata from the Kinect. WriteableBitmap是从Kinect的Depthdata创建的。 I am new to programming so there is certainly a better way, but I hope this will work too. 我是编程的新手,所以肯定有更好的方法,但是我希望这也可以。

Can anyone help me with that code? 谁能帮我提供该代码?

It is a little bit late, but I would like to add some more information. 有点晚了,但是我想补充一些信息。

The problem is that you are using a synchronous call which uses the UI thread, unlike all other synchronous calls, this call takes some time, and therefore, your application is frozen until the call will finish. 问题在于,您正在使用使用UI线程的同步调用,与所有其他同步调用不同,此调用需要一些时间,因此,您的应用程序将被冻结,直到调用完成。

You need to use an asynchronous call, so that your UI thread will be free, so the UI will not be frozen. 您需要使用异步调用,以便您的UI线程是空闲的,因此不会冻结UI。

There are many ways to make an asynchronous calls, such as opening a new task, thread, or my preferable way, is to use the async await, which is very great - you can write a synchronous code, and to add async and await in the right places, and woops - it is an asynchronous code! 进行异步调用的方法有很多,例如打开一个新任务,线程,或者我更喜欢的方法是使用async await,这非常好-您可以编写同步代码,并在其中添加async和await在正确的地方,然后跳-这是一个异步代码!

To read more about async await click here . 要了解有关异步等待的更多信息,请单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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