Iam using the Avalonia UI Framework to build a dotnet core MVVM app.
I want to display frames from a WebCam and created a simple 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:
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." while resizing the application. StackTrace
How can I properly dispose the old bitmap instances so that the GC doesn't have much to do?
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. This is why you choose MVVM in first place: view after transformation of model, transform before commiting to model. It will probably be a good idea to switch to MVC for web cam experience instead.