mono / SkiaSharp

SkiaSharp is a cross-platform 2D graphics API for .NET platforms based on Google's Skia Graphics Library. It provides a comprehensive 2D API that can be used across mobile, server and desktop models to render images.
MIT License
4.39k stars 535 forks source link

SkiaSharp could dispose objects too early #1880

Open laurenceSaes opened 2 years ago

laurenceSaes commented 2 years ago

Skia objects, like SkiaSharp.SKPaint, have disposable Skia properties that are retrieved based on their underlying C++ objects. The C# owner class does not have any reference to the C# equivalent of this property. This could result in too early garbage collection of dependent objects. This dispose action will call the C# destructor and free all allocated memory while the property is still in use.

See for example the following scenario:

An alternative fault situation:

The SKPaint.Shader property:

public SKShader Shader
{
  get => SKShader.GetObject(SkiaApi.sk_paint_get_shader(this.Handle));
  set => SkiaApi.sk_paint_set_shader(this.Handle, value == null ? IntPtr.Zero : value.Handle);
}

The SkiaSharp.SKPaint class should hold a reference to the C# Shader to prevent garbage collection.

An example of the alternative situation, this results in the following fatal crash:

image

Version information:

DamianSuess commented 1 year ago

I too am getting the same error with .NET MAUI on WinUI/UWP.

image