-
Notifications
You must be signed in to change notification settings - Fork 201
[Fix]IDisposable Analyzer Warnings #545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR removes global IDisposable analyzer warning suppressions and implements proper resource disposal patterns throughout the codebase. The changes address 89 files by adding IDisposable implementations, using statements for temporary resources, and documenting legitimate non-disposal cases with pragma suppressions.
Key Changes
- Removed global NoWarn suppressions for 9 IDisposable analyzer rules from the .csproj file
- Implemented IDisposable pattern on ~35 sample page classes and utility classes
- Applied using statements for ~60 temporary disposable objects (SessionOptions, CancellationTokenSource, HttpClient responses, bitmaps, streams)
- Added pragma suppressions with explanatory comments for ~60 legitimate non-disposal cases (external processes, system resources, ownership transfers)
- Optimized HttpClient usage by converting to static singleton pattern in GithubApi and HuggingFaceApi
- Added unit tests validating bitmap lifecycle management
Reviewed changes
Copilot reviewed 83 out of 83 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| AIDevGallery.csproj | Removed global IDisposable warning suppressions |
| ModelDownload.cs | Implemented proper virtual Dispose pattern with sealed derived classes |
| HuggingFaceApi.cs, GithubApi.cs | Changed to static HttpClient singleton |
| All WCR API samples | Added IDisposable implementation and CTS disposal |
| All Open Source Model samples | Added IDisposable implementation and resource cleanup |
| WhisperWrapper.cs | Changed SessionOptions to using statement |
| StableDiffusion code files | Added using for SessionOptions and disposal of previous instances |
| Shimmer.xaml.cs | Complete IDisposable implementation for composition resources |
| OpacityMask.xaml.cs | Added IDisposable with proper composition resource disposal |
| HoverLight.cs | Added IDisposable with composition resource cleanup |
| BitmapFunctions.cs | Added pragma suppressions for stream wrapper methods |
| Program.cs | Wrapped Semaphore in using statement |
| Process.Start calls | Added pragma suppressions for external process launches |
| ResourceLifecycleTests.cs | New unit tests for bitmap lifecycle validation |
Comments suppressed due to low confidence (1)
AIDevGallery/Samples/WCRAPIs/KnowledgeRetrieval.xaml.cs:1
- Corrected spelling of 'Sauté' from 'Saut�'.
- Remove duplicate cleanup code in SampleContainer finally block - Use static HttpClient in MyImage to prevent socket exhaustion - Remove premature disposal of AsRandomAccessStream wrapper in DefaultSVGRenderer
- Remove duplicate cleanup code in SampleContainer finally block - Use static HttpClient in MyImage to prevent socket exhaustion - Remove premature disposal of AsRandomAccessStream wrapper in DefaultSVGRenderer Co-authored-by: Milly Wei (from Dev Box) <yuanwei@microsoft.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 83 out of 83 changed files in this pull request and generated 24 comments.
Comments suppressed due to low confidence (1)
AIDevGallery/Controls/SampleContainer.xaml.cs:67
- This variable is manually disposed in a finally block - consider a C# using statement as a preferable resource management technique.
private CancellationTokenSource? _sampleLoadingCts;
|
@weiyuanyue I've opened a new pull request, #552, to work on those changes. Once the pull request is ready, I'll request review from you. |
) * Initial plan * Clarify pragma warning comment in MagicEraser The comment now correctly explains that outputBitmap's ownership is transferred to become the new _inputBitmap value, not to the old _inputBitmap. Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 83 out of 83 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (1)
AIDevGallery/Controls/SampleContainer.xaml.cs:67
- This variable is manually disposed in a finally block - consider a C# using statement as a preferable resource management technique.
private CancellationTokenSource? _sampleLoadingCts;
|
@weiyuanyue I've opened a new pull request, #553, to work on those changes. Once the pull request is ready, I'll request review from you. |
…ty class - Created ProcessHelper.cs with OpenUrl() and OpenFolder() methods - Centralized all Process.Start calls for external processes - Replaced 16+ scattered #pragma warning disable IDISP004 with a single location - Fixed null reference warning in ModelSelectionControl - Removed unnecessary System.Diagnostics using statements - IDISP004 rule still active for other IDisposable types
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 85 out of 85 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (2)
AIDevGallery/Samples/WCRAPIs/KnowledgeRetrieval.xaml.cs:1
- Corrected spelling of 'Sauté' (fixed accent character encoding).
AIDevGallery/Samples/SharedCode/Controls/SmartPasteForm.cs:1 - Variable name 'outputMessage' should reflect that it's a StringBuilder, not a string. Consider renaming to 'outputMessageBuilder' for clarity.
| var cts = _sampleLoadingCts; | ||
| if (cts == null) | ||
| { | ||
| _sampleLoadingCts.Cancel(); | ||
| _sampleLoadingCts = null; | ||
| return; | ||
| } | ||
|
|
||
| _sampleLoadingCts = null; | ||
| using (cts) | ||
| { | ||
| cts.Cancel(); | ||
| } |
Copilot
AI
Jan 13, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The early return when cts is null makes the subsequent code unreachable in that case, but the pattern of nulling out _sampleLoadingCts before disposing creates a potential race condition if CancelCTS is called concurrently. Consider using a lock or ensuring thread safety.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot open a new pull request to apply changes based on this feedback
|
@weiyuanyue I've opened a new pull request, #562, to work on those changes. Once the pull request is ready, I'll request review from you. |
* Initial plan * Fix race condition in CancelCTS with thread-safe lock Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 85 out of 85 changed files in this pull request and generated 7 comments.
Comments suppressed due to low confidence (2)
AIDevGallery/Samples/WCRAPIs/KnowledgeRetrieval.xaml.cs:171
- The
ctsfield can be accessed and disposed from multiple places without synchronization (lines 155, 169-171, 304). This creates a race condition ifCancelResponseis called while another thread is accessing or disposingcts. Consider adding synchronization using a lock or ensuring single-threaded access toctsoperations.
AIDevGallery/Controls/OpacityMask.xaml.cs:111 - The
GetVisualBrushmethod creates a newvisualSurfaceandsizeAnimationeach time it's called, but the old values are passed in asrefparameters. The caller disposes the old values before calling this method, but then this method creates new ones and returns aCompositionSurfaceBrushthat holds references to them. If the caller doesn't properly track and dispose the brush or ifOnApplyTemplateis called multiple times, this could lead to leaking thevisualSurfaceandsizeAnimationobjects that are created but whose references are now held only by the returned brush. Consider ensuring the brush is also properly tracked and disposed.
private static CompositionBrush GetVisualBrush(UIElement element, ref CompositionVisualSurface? visualSurface, ref ExpressionAnimation? sizeAnimation)
{
Visual visual = ElementCompositionPreview.GetElementVisual(element);
Compositor compositor = visual.Compositor;
// Create visual surface and animation
visualSurface = compositor.CreateVisualSurface();
visualSurface.SourceVisual = visual;
sizeAnimation = compositor.CreateExpressionAnimation($"{nameof(visual)}.Size");
sizeAnimation.SetReferenceParameter(nameof(visual), visual);
visualSurface.StartAnimation(nameof(visualSurface.SourceSize), sizeAnimation);
CompositionSurfaceBrush brush = compositor.CreateSurfaceBrush(visualSurface);
visual.Opacity = 0;
return brush;
}
|
@weiyuanyue I've opened a new pull request, #564, to work on those changes. Once the pull request is ready, I'll request review from you. |
|
@weiyuanyue I've opened a new pull request, #565, to work on those changes. Once the pull request is ready, I'll request review from you. |
* Initial plan * Fix SA1214 and IDISP003 analyzer errors in SampleContainer Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: weiyuanyue <176483933+weiyuanyue@users.noreply.github.com>
Summary
This PR fixes all IDisposable analyzer warnings in the AIDevGallery directory by removing global warning suppressions and properly implementing resource disposal patterns. The changes improve memory management, prevent resource leaks, and follow .NET best practices.
Problem
The project had global suppressions for 9 IDisposable analyzer rules:
These suppressions masked potential resource leaks and memory management issues across 89 files.
Solution
1. Removed Global Warning Suppressions
File:
AIDevGallery.csprojRemoved the global NoWarn configuration to enforce proper resource management.
2. Implemented IDisposable Pattern
Modified: ~35 files
Added proper IDisposable implementation to classes that manage disposable resources:
_disposedflagExample files:
3. Applied Using Statements
Modified: ~60 locations
Used
usingstatements for temporary disposable objects:4. Suppressed Valid Non-Dispose Cases
Modified: ~60 locations with clear comments
Added
#pragma warning disablewith explanatory comments for legitimate cases:a) External Process Lifecycle
b) System Resources
c) Ownership Transfer
5. Optimized HttpClient Usage
Files:
GithubApi.cs,HuggingFaceApi.csChanged from creating new HttpClient instances to static singleton:
Benefits:
Files with Special Handling
1. Stream Wrappers (BitmapFunctions.cs)
2. Composition Resources (HoverLight.cs, AmbLight.cs, OpacityMask.cs)
3. Ownership Transfer (ModelDownloadQueue, SvgImageSource)
Manual Testing Checklist
Breaking Changes
None. This is a code quality improvement with no API changes.
Migration Guide
Not applicable. No changes to public APIs or user-facing behavior.
Benefits
1. Memory Management
2. Code Quality
3. Performance
4. Maintainability
5. Reliability
References
Microsoft Documentation
IDisposable Analyzer Rules
Related PR