Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Fix issue 15213: Bitmap finalized during Image.Save(Stream, ImageFormat) leaks native GDI+ memory - #15254

Merged
SimonZhao888 merged 3 commits into
dotnet:mainfrom
SimonZhao888:Fix_Issue_15213
Nov 10, 2026
Merged

SimonZhao888 merged 3 commits into
dotnet:mainfrom
SimonZhao888:Fix_Issue_15213

Conversation

@SimonZhao888

@SimonZhao888 SimonZhao888 commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Fixes #15213

Root Cause

When Image.Save(Stream, ImageFormat) executes the internal stream-saving path, the Image object is not guaranteed to remain alive during the call to the native GdipSaveImageToStream function. Under specific timing conditions, the JIT compiler or Garbage Collector (GC) may trigger finalization of the Image object prematurely, creating a race condition with the native save operation; this results in the failure to release—or the loss of—underlying GDI+ image resources, manifesting as a native memory leak (where significant memory remains unrecovered).

Proposed changes

Within CoreImageExtensions.Save(this IImage image, Stream stream, ...) of System.Private.Windows.GdiPlus, wrap GdipSaveImageToStream in a try/finally block and call GC.KeepAlive(image) in the finally block.

Customer Impact

The correction avoids abnormal native memory growth in Save(Stream, ImageFormat) under high-pressure/specific GC timings, reducing memory risks and potential stability issues in long-duration or batch image processing scenarios.

The impact on existing behavioral compatibility is minimal (only extending object survival to the end of the method), and should not change functional results or introduce visible behavioral differences.

Regression?

  • Yes

Risk

  • Mini

Screenshots

Before

image

After

image

Test methodology

  • Manual

Test environment(s)

  • 11.0.0-rc.2.26509.113
Microsoft Reviewers: Open in CodeFlow

Simon Zhao (BEYONDSOFT CONSULTING INC) added 2 commits October 12, 2026 16:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The regression test baseline can be contaminated by pending finalizers from earlier tests.

1 open finding
What changed in this PR

Prevents premature Image finalization during native GDI+ stream saves.

Changes:

  • Keeps IImage alive through GdipSaveImageToStream.
  • Adds native-memory regression coverage.
File Description
CoreImageExtensions.cs Extends image lifetime through native save.
ImageTests.cs Tests memory growth across collections.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 37.84861%. Comparing base (77d6ad3) to head (7b84515).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@              Coverage Diff              @@
##                main      #15254   +/-   ##
=============================================
  Coverage   37.84861%   37.84861%           
=============================================
  Files            246         246           
  Lines           9789        9789           
  Branches        1031        1031           
=============================================
  Hits            3705        3705           
  Misses          5920        5920           
  Partials         164         164           
Flag Coverage Δ
Debug 37.84861% <ø> (ø)
production 40.04608% <ø> (ø)
test 20.64923% <ø> (ø)
unit 40.04608% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@SimonZhao888 SimonZhao888 added the waiting-review This item is waiting on review by one or more members of team label Oct 15, 2026
@kimsey0

kimsey0 commented Oct 21, 2026

Copy link
Copy Markdown

Once this lands, it would be great to have it backported to release/11.0 and release/10.0 (LTS). We're seeing a production memory leak caused by a third-party rendering library we can't change, and we can't pin System.Drawing.Common 8.x.

@KlausLoeffelmann KlausLoeffelmann left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.
Since this is leaking and a burden for Customers - let's please backport this to .NET 11 next service and .NET 10 next service.

@SimonZhao888
SimonZhao888 merged commit f930f5d into dotnet:main Nov 10, 2026
8 checks passed
@SimonZhao888
SimonZhao888 deleted the Fix_Issue_15213 branch November 10, 2026 01:17
@dotnet-policy-service dotnet-policy-service Bot removed the waiting-review This item is waiting on review by one or more members of team label Nov 10, 2026
SimonZhao888 added a commit to KlausLoeffelmann/winforms that referenced this pull request Nov 10, 2026
…at) leaks native GDI+ memory (dotnet#15254)

* Fix issue 15213: Bitmap finalized during Image.Save(Stream, ImageFormat) leaks native GDI+ memory

* Add test case

* Handle feedback

---------

Co-authored-by: Simon Zhao (BEYONDSOFT CONSULTING INC) <v-weidzh@microsoft.com>
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 10, 2026
@SimonZhao888

Copy link
Copy Markdown
Member Author

/backport to release/10.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/10.0 (link to workflow run)

LeafShi1 added a commit that referenced this pull request Dec 3, 2026
…5386)

## Description

Backports seven WinForms fixes from main to release/11.0 for inclusion
in the December 2026 .NET 11 servicing release.
These changes address several issues affecting control rendering,
layout, DPI scaling, selection handling, and native resource management.

## Fixes

- #15325
- #15212
- #15361
- #15270
- #15207
- #15254
- #15390

##  Proposed Changes

This PR cherry-picks the following fixes:

1. **UpDown sizing and focus indicator (#15325)**
- Fixes sizing issues and focus-indicator flickering in UpDown controls
when using .NET 11 visual styles.
2. **DomainUpDown and NumericUpDown height (#15212)**
- Fixes an issue where these controls incorrectly allow height changes
instead of preserving their expected height in VisualStylesMode.Net11.
3. **ListBox selection handling (#15361)**
- Fixes an IndexOutOfRangeException in ListBox.RefreshItems caused by a
stale selected-item count cache.
4. **ToggleSwitch checked thumb color (#15270)**
   - Corrects the checked thumb color in both light and dark modes.
5. **UpDown DPI scaling (#15207)**
   - Fixes incorrect scaling of UpDown buttons when DPI changes.
6. **Bitmap native memory leak (#15254)**
- Fixes a native GDI+ memory leak when a Bitmap is finalized during
Image.Save(Stream, ImageFormat).
7. **ToggleSwitch animation improvements**
- Shortens ToggleSwitch state-transition animations to improve
responsiveness.

## Customer Impact

These fixes address issues that can affect applications running on .NET
11:

- **Visual and layout issues:** Incorrect control sizing,
focus-indicator flickering, and inconsistent ToggleSwitch rendering can
negatively affect the user experience.
- **High-DPI environments:** UpDown buttons may scale incorrectly when
applications move between displays with different DPI settings.
- **Application reliability:** The ListBox issue can cause an
IndexOutOfRangeException during item refresh operations.
- **Resource management:** The Bitmap issue can cause native GDI+ memory
to remain allocated after the affected save operation.

The changes improve control rendering, layout consistency, DPI scaling,
and application reliability. Existing applications will receive the
fixes without requiring code changes. Some visual and behavioral
differences may be noticeable in affected controls, particularly those
using .NET 11 visual styles.

## Regression?

**Partially.**

Several fixes address issues associated with the new .NET 11 visual
styles, particularly control sizing, focus indicators, and ToggleSwitch
rendering.
The remaining fixes address functional correctness, DPI scaling, and
native resource management issues.
Not all seven issues have been confirmed as regressions introduced in
.NET 11.

## Testing
All seven included fixes have been validated.

- Verified the fixes for all seven cherry-picked PRs.
- Confirmed that the corresponding GitHub issues are resolved.
- No new regression issues were identified during validation.

## Risk

**Minimal**

- These changes have already been merged into main.
- All seven fixes have been individually validated.
- No new regressions were identified during testing.
- Most changes are targeted fixes for specific control behaviors.
- The ListBox and Bitmap fixes affect functional behavior and native
resource management, therefore, additional regression tests have been
added.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regression: Bitmap finalized during Image.Save(Stream, ImageFormat) leaks native GDI+ memory

5 participants