dotnet / winforms

Windows Forms is a .NET UI framework for building Windows desktop applications.
MIT License
4.42k stars 986 forks source link

Do Not Block Thread When No Message Loop Running #12236

Closed lonitra closed 1 month ago

lonitra commented 1 month ago

Related https://github.com/dotnet/winforms/issues/11944

When a synchronization context has been established, but no message loop is running and a message is sent from another thread, this will cause a deadlock as the thread that sent the message is waiting for work to be done, but there will never be a response so long no message loop is running. Though it is the responsibility of the user to ensure a message loop will start eventually, we should not block the thread in case message loop has not run yet. In this particular repro issue presents, SystemEvents thread cannot shut down as it is waiting on WinFormsSynchronizationContext, which is waiting for another thread to respond to OnUserPreferenceChanged event

This change involves checking if a message loop is running before committing to waiting for a response to avoid blocking the thread indefinitely.

Manually tested scenarios:

Draft for more testing.

Microsoft Reviewers: Open in CodeFlow