| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="SynchronizationContextCollectionEventDispatcher.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Threading; |
| | | 9 | | |
| | | 10 | | namespace MyNet.Collections; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Dispatches events through a synchronization context, typically the UI context. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// Initializes a new instance of the <see cref="SynchronizationContextCollectionEventDispatcher"/> class. |
| | | 17 | | /// </remarks> |
| | | 18 | | /// <param name="context">The synchronization context to use.</param> |
| | | 19 | | public sealed class SynchronizationContextCollectionEventDispatcher(SynchronizationContext? context) : ICollectionEventD |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// Captures the current synchronization context or falls back to immediate dispatch. |
| | | 23 | | /// </summary> |
| | | 24 | | public static ICollectionEventDispatcher CaptureCurrentOrImmediate() |
| | 3 | 25 | | => SynchronizationContext.Current is null |
| | 3 | 26 | | ? ImmediateCollectionEventDispatcher.Default |
| | 3 | 27 | | : new SynchronizationContextCollectionEventDispatcher(SynchronizationContext.Current); |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Checks if the current thread has access to the configured synchronization context, allowing for optimized dispat |
| | | 31 | | /// </summary> |
| | | 32 | | /// <returns>True if the current thread has access to the synchronization context; otherwise, false.</returns> |
| | 6 | 33 | | public bool CheckAccess() => context is null || SynchronizationContext.Current == context; |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public void Dispatch(Action action) |
| | | 37 | | { |
| | 6 | 38 | | ArgumentNullException.ThrowIfNull(action); |
| | | 39 | | |
| | 6 | 40 | | if (context is null) |
| | | 41 | | { |
| | 3 | 42 | | action(); |
| | 3 | 43 | | return; |
| | | 44 | | } |
| | | 45 | | |
| | 3 | 46 | | context.Post(_ => action(), null); |
| | 3 | 47 | | } |
| | | 48 | | } |
| | | 49 | | |