I was creating a C# WPF custom control library, My library uses DisplaySettingsChanged
event from SystemEvents Class, In the Docs Microsoft mentioned about detaching the Event Handler.
Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.
So will it be possible to use lambda expression without causing memory leak in the program ( without using -= ).
Which means :
Can I use this:
SystemEvents.DisplaySettingsChanged += (_, _) =>
{
// My code Here
};
instead of using this:
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
SystemEvents.DisplaySettingsChanged -= OnDisplaySettingsChanged; // Calling this in Dispose Method
Full Code
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
namespace FluentCompositor.Core
{
public sealed class CompositionMetrics : IDisposable
{
private readonly HwndSource hwndSource;
public CompositionMetrics(HwndSource source)
{
hwndSource = source;
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged; //added event handler over here
}
private void OnDisplaySettingsChanged(object? sender, EventArgs e)
{
throw new NotImplementedException();
}
public void Dispose()
{
SystemEvents.DisplaySettingsChanged -= OnDisplaySettingsChanged; // disposing event handler here
}
#region Properties
public int Width
{
get;
private set;
}
public int Height
{
get;
private set;
}
public double ScaleFactor
{
get;
private set;
}
#endregion
}
}