Skip to content

Commit

Permalink
Add comment to Suppress method
Browse files Browse the repository at this point in the history
  • Loading branch information
drewnoakes committed May 2, 2024
1 parent 3213f37 commit 2a0c631
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@ namespace Microsoft.VisualStudio;

internal static class SynchronizationContextUtil
{
/// <summary>
/// Sets a <see langword="null"/> <see cref="SynchronizationContext"/>, and restores
/// whatever context was <see cref="SynchronizationContext.Current"/> when disposed.
/// </summary>
/// <remarks>
/// This method is intended for use in tests where we use JTF and test code that
/// wants to switch to the main thread. Some of our tests don't actually construct
/// JTF in a way that creates a main thread that can be switched to. For these cases,
/// whatever thread creates the <see cref="Threading.JoinableTaskContext"/> is considered
/// the main thread. In unit tests, it's likely this is a thread pool thread, and
/// attempting to switch to the main thread will land on another thread pool thread.
/// <see cref="Threading.JoinableTaskFactory.SwitchToMainThreadAsync(CancellationToken)"/>
/// attempts to validate the switch was successful, and throws when not. This causes test
/// failures where we don't have a main thread to switch to. A workaround for this is
/// to suppress the synchronization context, which disables the check and allows the test
/// to pass.
/// </remarks>
/// <returns>An object that restores the previous synchronization context when disposed.</returns>
public static IDisposable Suppress()
{
SynchronizationContext old = SynchronizationContext.Current;
Expand Down

0 comments on commit 2a0c631

Please sign in to comment.