Created
October 8, 2025 05:55
-
-
Save yamamaya/eed12b2115a38f9d1bf8731e8c57d77d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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