Skip to content

Suppress finalizeation of ThreadMethodEntry class. Fix #10361. - #10460

Merged
lonitra merged 4 commits into
dotnet:mainfrom
kirsan31:ThreadMethodEntry
Feb 9, 2024
Merged

lonitra merged 4 commits into
dotnet:mainfrom
kirsan31:ThreadMethodEntry

Conversation

@kirsan31

@kirsan31 kirsan31 commented Dec 11, 2023 •

Copy link
Copy Markdown
Contributor

Fixes #10361
After every call to BeginInvoke/Invoke instance of ThreadMethodEntry will end up in Freachable queue.

Proposed changes

- Register for finalization only when WH is allocated.
- SuppressFinalize after WH disposed.

  • Remove ThreadMethodEntry finalizer.
  • Dispose WaitHandle during Invoke call.

Customer Impact

  • ThreadMethodEntry will not end in Freachable queue - GC will be more faster - overall improve performance.

Regression?

  • No

Risk

Minimal.

Test methodology

New UT added.
I would like to add tests for the triggering of the finalizer, but unfortunately we cannot correctly handle exceptions in it :( That is, the only option is to add some kind of debug only test logic - is this necessary?


P.S. I have many test failure (not related to this PR) on my pc:
testError


P.P.S. I have build error with VS 17.8.3:

21>MSBuild version 17.8.3+195e7f5a3 for .NET Framework
21>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(254,5): error MSB8066: Custom build for 'D:\Projects\winforms\artifacts\obj\NativeTests\x86\Debug\CMakeFiles\6366f68e1e32f772e531aff683e51b2d\Contract_i.c.rule' exited with code 9009. [D:\Projects\winforms\artifacts\obj\NativeTests\x86\Debug\NativeTests.vcxproj]
21>C:\Users\_\.nuget\packages\microsoft.dotnet.cmake.sdk\9.0.0-beta.23607.2\build\Microsoft.DotNet.CMake.Sdk.targets(190,5): error MSB3073: The command "
21>C:\Users\_\.nuget\packages\microsoft.dotnet.cmake.sdk\9.0.0-beta.23607.2\build\Microsoft.DotNet.CMake.Sdk.targets(190,5): error MSB3073:       call "D:\Projects\winforms\eng\init-vs-env.cmd" 
21>C:\Users\_\.nuget\packages\microsoft.dotnet.cmake.sdk\9.0.0-beta.23607.2\build\Microsoft.DotNet.CMake.Sdk.targets(190,5): error MSB3073:       
21>C:\Users\_\.nuget\packages\microsoft.dotnet.cmake.sdk\9.0.0-beta.23607.2\build\Microsoft.DotNet.CMake.Sdk.targets(190,5): error MSB3073:       cmake --build "D:\Projects\winforms\artifacts\obj\NativeTests\x86\Debug" --target install  --config Debug -- -verbosity:quiet /p:PlatformToolset=%__PlatformToolset%
21>C:\Users\_\.nuget\packages\microsoft.dotnet.cmake.sdk\9.0.0-beta.23607.2\build\Microsoft.DotNet.CMake.Sdk.targets(190,5): error MSB3073:       " exited with code 1.
21>Done building project "NativeTests.proj" -- FAILED.
Microsoft Reviewers: Open in CodeFlow

@kirsan31
kirsan31 requested a review from a team as a code owner December 11, 2023 13:02
@ghost ghost assigned kirsan31 Dec 11, 2023
@kirsan31
kirsan31 marked this pull request as draft December 11, 2023 14:15
@kirsan31 kirsan31 changed the title Fix #10361. And one more bug. Fix #10361. Dec 11, 2023
@kirsan31
kirsan31 marked this pull request as ready for review December 11, 2023 15:27
@kirsan31 kirsan31 changed the title Fix #10361. Suppress finalizeation of ThreadMethodEntry class. Fix #10361. Dec 29, 2023

@lonitra lonitra 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.

Thank you for your patience! Added some small comments

@lonitra lonitra added the waiting-author-feedback The team requires more information from the author label Jan 12, 2024
@ghost ghost removed the waiting-author-feedback The team requires more information from the author label Jan 14, 2024
@kirsan31
kirsan31 requested a review from lonitra January 14, 2024 11:23
@codecov

codecov Bot commented Jan 14, 2024 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (da7b855) 72.61924% compared to head (d8f34f4) 72.62188%.
Report is 22 commits behind head on main.

Additional details and impacted files
@@                 Coverage Diff                 @@
##                main      #10460         +/-   ##
===================================================
+ Coverage   72.61924%   72.62188%   +0.00263%     
===================================================
  Files           2931        2931                 
  Lines         620286      620280          -6     
  Branches       46942       46941          -1     
===================================================
+ Hits          450447      450459         +12     
+ Misses        161478      161461         -17     
+ Partials        8361        8360          -1     
Flag Coverage Δ
Debug 72.62188% <100.00000%> (+0.00263%) ⬆️
production 43.61267% <100.00000%> (+0.00511%) ⬆️
test 97.37519% <ø> (ø)

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

lonitra
lonitra previously approved these changes Jan 16, 2024

@lonitra lonitra 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.

LGTM!

@lonitra lonitra added the ready-to-merge PRs that are ready to merge but worth notifying the internal team. label Jan 16, 2024

@JeremyKuhne JeremyKuhne 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.

In general this looks good, just a few questions / comments.

Assert.Throws<TargetParameterCountException>(() => control.Invoke(method, Array.Empty<object>()));
}

#if DEBUG

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'm confused as to why this is DEBUG only. The comment seems to tell me that these tests will Debug.Fail.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm confused as to why this is DEBUG only. The comment seems to tell me that these tests will Debug.Fail.

Yes, so these tests will never fail in release mode. And I put #if DEBUG to indicate that test actual only in debug build - am I wrong?

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.

@kirsan31 There is probably at least some value in running the tests in release on the slim chance that they fail. If we're concerned about test performance I'd rather see these conditionalized in code.

@ghost ghost added waiting-author-feedback The team requires more information from the author and removed waiting-author-feedback The team requires more information from the author labels Jan 16, 2024
@lonitra
lonitra requested a review from JeremyKuhne January 18, 2024 17:42
@lonitra lonitra removed the ready-to-merge PRs that are ready to merge but worth notifying the internal team. label Jan 18, 2024
@kirsan31

Copy link
Copy Markdown
Contributor Author

@JeremyKuhne

  • Suggestions implemented.
  • Fixed some tests (they never failed). P.s. it's hard to have no way to check for failures :( For example this code:
    using (Control control = new())
    {
        control.CreateControl();
        Action method = () => { };
        IAsyncResult res = control.BeginInvoke(method);
        WaitHandle waitHandle = res.AsyncWaitHandle;
        while (!waitHandle.WaitOne(1))
        {
            Application.DoEvents();
        }
    }
    
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    will not trigger ThreadMethodEntry finalization for some reason 🤷‍♂️ And I had to move the code to a local function...
  • Question about #if DEBUG is still actual.

Also I have noticed some interesting thing. In ManualResetEventPrivate I use:

protected override void Dispose(bool explicitDisposing)
{
    base.Dispose(explicitDisposing);
    if (explicitDisposing)
    {
        // The owner (ThreadMethodEntry) need to free only this waitHandle.
        // But ThreadMethodEntry can't be Disposed directly because it exposed though IAsyncResult interface.
        // So after freeing this waitHandle we mark owner ThreadMethodEntry to suppress finalization.
        GC.SuppressFinalize(_owner);
    }
}

and explicitDisposing here is always true (even when called from finalizer):

~ThreadMethodEntry()
{
    _resetEvent?.Close();
    Debug.Fail($"{nameof(ThreadMethodEntry)} finalization hit!");
}

Due to WaitHandle code:

public virtual void Close() => Dispose();

protected virtual void Dispose(bool explicitDisposing)
{
    _waitHandle?.Close();
}

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

could this be a problem?

@JeremyKuhne

Copy link
Copy Markdown
Member

@kirsan31

will not trigger ThreadMethodEntry finalization for some reason 🤷‍♂️ And I had to move the code to a local function...

Presumably it is still rooted in a local? At least historically I remember the GC keeping all locals rooted to the end of a stack frame in debug.

{
// If something new is added here, it is necessary to reconsider the conditions of finalization.
// Look GC.SuppressFinalize(this); in constructor and GC.ReRegisterForFinalize(this); in AsyncWaitHandle.
_resetEvent?.Close();

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.

@kirsan31 I hadn't really internalized that we're touching a class in the finalizer. Why do we even have a finalizer? The event has its own SafeHandle that should take care of things.

@kirsan31 kirsan31 Jan 29, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ha, I think you're right - why did I decide to overcomplicate everything? 🤦‍♂️🤦‍♂️🤦‍♂️ Indeed, removing the destructor and disposing WaitHandle after Invoke should solve all the problems...
I'll correct...

@kirsan31
kirsan31 requested a review from JeremyKuhne February 3, 2024 12:41
@elachlan elachlan added waiting-on-team This work item needs to be discussed with team or is waiting on team action in order to proceed waiting-review This item is waiting on review by one or more members of team and removed waiting-on-team This work item needs to be discussed with team or is waiting on team action in order to proceed labels Feb 7, 2024
@lonitra
lonitra merged commit e837d07 into dotnet:main Feb 9, 2024
@dotnet-policy-service dotnet-policy-service Bot added this to the 9.0 Preview2 milestone Feb 9, 2024
@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 Feb 9, 2024
KlausLoeffelmann pushed a commit to KlausLoeffelmann/winforms that referenced this pull request Mar 5, 2024
…otnet#10460)

* Fix dotnet#10361.

* Suggestions implemented.

* Suggestions implemented. Tests fixes.

* ThreadMethodEntry finalizer removed. Tests removed.
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 11, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Suppress finalizeation of ThreadMethodEntry class

4 participants