Skip to content

Wrap all accesses to cancellation token source in PackageItemViewModel in try-catch blocks to handle ObjectDisposedException gracefully - #6918

Closed
jebriede wants to merge 1 commit into
devfrom
dev-jebriede-FixObjectDisposedInViewModel
Closed

jebriede wants to merge 1 commit into
devfrom
dev-jebriede-FixObjectDisposedInViewModel

Conversation

@jebriede

@jebriede jebriede commented Nov 4, 2025

Copy link
Copy Markdown
Contributor

Wrap all accesses to _cancellationTokenSource.Token in try-catch blocks to handle ObjectDisposedException gracefully

Bug

Fixes: https://github.com/NuGet/Client.Engineering/issues/3499

Description

The PackageItemViewModel class was throwing ObjectDisposedException when code attempted to access the CancellationTokenSource after the ViewModel had been disposed. This exception was being logged as a fault in telemetry.

Root Cause

The issue occurred when:

  1. The PackageItemViewModel's Dispose() method was called, which disposed the _cancellationTokenSource
  2. Async methods that had already started (or were about to start) attempted to access _cancellationTokenSource.Token
  3. Accessing the Token property of a disposed CancellationTokenSource throws ObjectDisposedException

Solution

The fix wraps all accesses to _cancellationTokenSource.Token in try-catch blocks to handle ObjectDisposedException gracefully. When the CancellationTokenSource is disposed:

  1. GetVersionsAsync methods: Return empty collections instead of throwing
  2. Async operations (ReloadPackageVersionsAsync, RunOperationAsync): Exit gracefully as if cancelled
  3. GetDetailedPackageSearchMetadataAsync: Throws OperationCanceledException (which is already handled by callers)
  4. UpdateInstalledPackagesVulnerabilities: Does not start new operations

This approach ensures that:

  • ObjectDisposedException is never propagated to telemetry
  • The behavior is semantically correct (treating disposed state as cancelled)
  • No existing functionality is broken

PR Checklist

  • Meaningful title, helpful description and a linked NuGet/Home issue
  • Added tests
  • Link to an issue or pull request to update docs if this PR changes settings, environment variables, new feature, etc.

…ocks to handle ObjectDisposedException gracefully
@jebriede
jebriede requested a review from a team as a code owner November 4, 2025 02:02
@jebriede jebriede changed the title Wrap all accesses cancellation token source in PackageItemViewModel in try-catch blocks to handle ObjectDisposedException gracefully Wrap all accesses to cancellation token source in PackageItemViewModel in try-catch blocks to handle ObjectDisposedException gracefully Nov 4, 2025
Comment on lines +518 to +526
try
{
cancellationToken = _cancellationTokenSource.Token;
}
catch (ObjectDisposedException)
{
// If the CancellationTokenSource is disposed, return empty collection
return Array.Empty<VersionInfoContextInfo>();
}

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.

I think we could centralize this pattern in a helper

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.

We can also null out the CancellationTokenSource to avoid the try catching ugliness.

CancellationToken cancellationToken;
try
{
cancellationToken = _cancellationTokenSource.Token;

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.

Could we maybe add bool _disposed = false to the PackageItemViewMidel and when the object is disposed set it true. That would allow methods that used the cancelation token to just check if _disposed and return an empty collection.

Comment on lines 791 to +796
private async Task RunOperationAsync(Func<CancellationToken, Task> func)
{
CancellationToken cancellationToken = _cancellationTokenSource.Token;
CancellationToken cancellationToken;
try
{
cancellationToken = _cancellationTokenSource.Token;

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.

Did you investigate changing the method signatures (all the methods affected in this PR) so that the cancellation token is passed in, rather than getting it from the token source?

Even if this try-catch makes the fault telemetry go away, I'm concerned that we still have a code correctness issue.

PM UI closing is one reason PM UI disposes cancellation token sources, but another reason is when there's logic when we swap a token source with a new one (possibly when switching tabs, or on the browse tab when the search query changes). If there's a timing issue where async code uses _cancellationTokenSource after it's been disposed, I think it's possible it also accesses it after it's been swapped.

I've personally experienced issues when typing a search query immediately after opening PM UI and the search results that get displayed are wrong. Either showing the package source's top packages, as if I didn't type a search query at all, or the results clearly show that it only used the first few letters of the search query I ended up typing. It never occurred to me before, but now I wonder if it's related to async work scheduled that reads _cancellatinTokenSource.Token after the swap already happened.

As you know, the UI always runs callbacks (button clicks, search query box text changing) on the UI thread in synchronous methods. If these "entry point" methods are the only places that _cancellationTokenSource.Token is accessed, then I think we can be confident that there won't be "stale" async work that keeps running when we logically expect it to be cancelled. I expect most of these "entry point" methods will use JTF.RunAsync. If they capture the cancellation token before running JTF, and all async code gets passed the token, then we should solve the fault telemetry, but also fix correctness bugs.

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.

My vote is that if the code is good enough, we get this merged to fix the problem. I'd love to have more time to make the more in depth fix but since this is PM UI, I lean towards just getting the root issue solved so we can move on.

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.

I agree with Andy that we should try to capture the token, and minimize the amount of places with use the CTS.

For context, what Andy is referring to is https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource?view=net-9.0#thread-safety

Unfortunately I'm not sure that's a general solution because sometimes the calls are coming from the package manager control, sometimes from somewhere else.

fwiw, I don't care about fixing the telemetry issue that much, if all we're gonna do is hide the functional problem below.

If you'd rather not do the work that @zivkan is suggesting, I think we should just stop disposing instead. It does the same clean-up and we don't seem to be using CreateLinkedTokenSource that can cause some things to not be cleaned up.

See related aspnet/AspNetKatana#109

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.

fwiw, I don't care about fixing the telemetry issue that much, if all we're gonna do is hide the functional problem below.

If you'd rather not do the work that @zivkan is suggesting, I think we should just stop disposing instead.

I agree that I'm less concerned about the exception and one of the other options sounds better than hiding it.

Comment on lines 791 to +796
private async Task RunOperationAsync(Func<CancellationToken, Task> func)
{
CancellationToken cancellationToken = _cancellationTokenSource.Token;
CancellationToken cancellationToken;
try
{
cancellationToken = _cancellationTokenSource.Token;

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.

I agree with Andy that we should try to capture the token, and minimize the amount of places with use the CTS.

For context, what Andy is referring to is https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource?view=net-9.0#thread-safety

Unfortunately I'm not sure that's a general solution because sometimes the calls are coming from the package manager control, sometimes from somewhere else.

fwiw, I don't care about fixing the telemetry issue that much, if all we're gonna do is hide the functional problem below.

If you'd rather not do the work that @zivkan is suggesting, I think we should just stop disposing instead. It does the same clean-up and we don't seem to be using CreateLinkedTokenSource that can cause some things to not be cleaned up.

See related aspnet/AspNetKatana#109

catch (ObjectDisposedException)
{
// If the CancellationTokenSource is disposed, return empty collection
return Array.Empty<VersionInfoContextInfo>();

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.

Could this cause correctness issues?
Wouldn't it be more accurate throw an exception and tear it down instead of return a result potentially indicating things are fine?

Comment on lines +518 to +526
try
{
cancellationToken = _cancellationTokenSource.Token;
}
catch (ObjectDisposedException)
{
// If the CancellationTokenSource is disposed, return empty collection
return Array.Empty<VersionInfoContextInfo>();
}

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.

We can also null out the CancellationTokenSource to avoid the try catching ugliness.

@donnie-msft donnie-msft 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.

Great to see someone moving the needle on this type of issue! Left a +1 on a comment with two alternate approaches that sound better to me.

@dotnet-policy-service dotnet-policy-service Bot added the Status:No recent activity PRs that have not had any recent activity and will be closed if the label is not removed label Nov 12, 2025
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

This PR has been automatically marked as stale because it has no activity for 7 days. It will be closed if no further activity occurs within another 7 days of this comment. If it is closed, you may reopen it anytime when you're ready again, as long as you don't delete the branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Status:No recent activity PRs that have not had any recent activity and will be closed if the label is not removed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants