| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="SchedulerCollectionEventDispatcher.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Reactive.Concurrency; |
| | | 9 | | using MyNet.Collections; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Observable.Collections; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Adapter that bridges an Rx scheduler to the collection event dispatcher abstraction. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// Initializes a new instance of the <see cref="SchedulerCollectionEventDispatcher"/> class. |
| | | 18 | | /// </remarks> |
| | | 19 | | /// <param name="scheduler">The scheduler used to dispatch actions.</param> |
| | | 20 | | public sealed class SchedulerCollectionEventDispatcher(IScheduler scheduler) : ICollectionEventDispatcher |
| | | 21 | | { |
| | 9 | 22 | | private readonly IScheduler _scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler)); |
| | 9 | 23 | | private volatile int _schedulerThreadId = -1; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Checks if the current thread can invoke collection notifications without marshaling. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <returns><c>true</c> when already on the scheduler's execution context; otherwise <c>false</c>.</returns> |
| | | 29 | | public bool CheckAccess() |
| | | 30 | | { |
| | 12 | 31 | | if (ReferenceEquals(_scheduler, ImmediateScheduler.Instance) || |
| | 12 | 32 | | ReferenceEquals(_scheduler, CurrentThreadScheduler.Instance)) |
| | | 33 | | { |
| | 6 | 34 | | return true; |
| | | 35 | | } |
| | | 36 | | |
| | 6 | 37 | | var threadId = _schedulerThreadId; |
| | 6 | 38 | | return threadId >= 0 && threadId == Environment.CurrentManagedThreadId; |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | | 42 | | public void Dispatch(Action action) |
| | | 43 | | { |
| | 3 | 44 | | ArgumentNullException.ThrowIfNull(action); |
| | | 45 | | |
| | 3 | 46 | | _scheduler.Schedule(() => |
| | 3 | 47 | | { |
| | 3 | 48 | | _schedulerThreadId = Environment.CurrentManagedThreadId; |
| | 3 | 49 | | action(); |
| | 3 | 50 | | }); |
| | 3 | 51 | | } |
| | | 52 | | } |
| | | 53 | | |