Skip to content

Instantly share code, notes, and snippets.

@yamamaya
Created October 8, 2025 05:55
Show Gist options
  • Select an option

  • Save yamamaya/eed12b2115a38f9d1bf8731e8c57d77d to your computer and use it in GitHub Desktop.

Select an option

Save yamamaya/eed12b2115a38f9d1bf8731e8c57d77d to your computer and use it in GitHub Desktop.
namespace OaktreeLab.Utils.Common {
/// <summary>
/// Synchronous version of IProgress
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class SynchronousProgress<T> : IProgress<T> {
private readonly SynchronizationContext? _context;
private readonly Action<T> _handler;
public SynchronousProgress( Action<T> handler ) {
_context = SynchronizationContext.Current;
_handler = handler ?? throw new ArgumentNullException( nameof( handler ) );
}
/// <summary>
/// Reports progress. Blocks until the handler has completed.
/// </summary>
/// <param name="value"></param>
public void Report( T value ) {
if ( _context == null ) {
// No context: execute synchronously
_handler( value );
return;
}
if ( SynchronizationContext.Current == _context ) {
// Already on UI thread: invoke directly
_handler( value );
} else {
// Execute synchronously on the UI thread
_context.Send( _ => _handler( value ), null );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment