Skip to content

Commit

Permalink
#19 - fixing disposal, early GC to free memory
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeclayton committed Jul 18, 2023
1 parent c454ff4 commit 66b81e7
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/FancyMouse/UI/FancyMouseForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,7 @@ private void FancyMouseForm_KeyDown(object sender, KeyEventArgs e)
private void FancyMouseForm_Deactivate(object sender, EventArgs e)
{
this.Hide();

if (this.Thumbnail.Image is not null)
{
var tmp = this.Thumbnail.Image;
this.Thumbnail.Image = null;
tmp.Dispose();
}
this.ClearPreview();
}

private void Thumbnail_Click(object sender, EventArgs e)
Expand Down Expand Up @@ -199,7 +193,7 @@ public void ShowPreview()
this.OnPreviewImageCreated,
this.OnPreviewImageUpdated);
}
catch
finally
{
DrawingHelper.FreeDesktopDeviceContext(ref desktopHwnd, ref desktopHdc);
}
Expand All @@ -210,6 +204,22 @@ public void ShowPreview()
this.Activate();
}

private void ClearPreview()
{
if (this.Thumbnail.Image is null)
{
return;
}

var tmp = this.Thumbnail.Image;
this.Thumbnail.Image = null;
tmp.Dispose();

// force preview image memory to be released, otherwise
// all the disposed images can pile up without being GC'ed
GC.Collect();
}

/// <summary>
/// Resize and position the specified form.
/// </summary>
Expand All @@ -229,6 +239,7 @@ private void PositionForm(RectangleInfo bounds)

private void OnPreviewImageCreated(Bitmap preview)
{
this.ClearPreview();
this.Thumbnail.Image = preview;
}

Expand Down

0 comments on commit 66b81e7

Please sign in to comment.