[英]What is the proper way to dispose avalonia bitmap?
Iam using the Avalonia UI Framework to build a dotnet core MVVM app.我正在使用Avalonia UI 框架构建一个 dotnet 核心 MVVM 应用程序。
I want to display frames from a WebCam and created a simple WebCamViewModel:我想显示来自网络摄像头的帧并创建了一个简单的 WebCamViewModel:
public class WebCamViewModel : ViewModelBase
{
private Bitmap webCamImage;
public Bitmap WebCamImage
{
get { return webCamImage; }
private set { this.RaiseAndSetIfChanged(ref webCamImage, value); }
}
public WebCamViewModel(WebCamImageService webcamImageService)
{
webcamImageService.OnFrame += BitmapReceived;
}
public void BitmapReceived(Bitmap bitmap)
{
WebCamImage = bitmap;
}
}
I tried the naiv approach and dispose the old bitmap like this:我尝试了 naiv 方法并像这样处理旧位图:
public void BitmapReceived(Bitmap bitmap)
{
if (webCamImage != null) webCamImage.Dispose();
WebCamImage = bitmap;
}
I get System.NullReferenceException: "Object reference not set to an instance of an object."我收到 System.NullReferenceException:“未将对象引用设置为对象的实例。” while resizing the application.
在调整应用程序大小时。 StackTrace
堆栈跟踪
How can I properly dispose the old bitmap instances so that the GC doesn't have much to do?如何正确处理旧的位图实例,以便 GC 没有太多事情要做?
Is there a better approach to display dynamic changing image content?有没有更好的方法来显示动态变化的图像内容?
There is a couple of question exist:有几个问题存在:
public void Dispose()
{
_service.OnFrame -= BitmapReceived;
}
public event EventHandler<Bitmap> OnFrame
{
add
{
_service.OnFrame += value;
}
remove
{
_service.OnFrame -= value;
}
}
This way you can perform required transformations on Bitmap before you feed it to View.通过这种方式,您可以在将 Bitmap 提供给 View 之前对其执行所需的转换。 This is why you choose MVVM in first place: view after transformation of model, transform before commiting to model.
这就是您首先选择MVVM 的原因:模型转换后查看,提交模型之前转换。 It will probably be a good idea to switch to MVC for web cam experience instead.
切换到MVC以获得网络摄像头体验可能是个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.