optimize progress invocation

This commit is contained in:
Lightczx
2023-12-26 10:36:59 +08:00
parent 22a974408d
commit 371e469db7
4 changed files with 21 additions and 33 deletions

View File

@@ -1,45 +1,24 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Dispatching;
namespace Snap.Hutao.Core.Threading;
internal class DispatcherQueueProgress<T> : IProgress<T>
{
private readonly SynchronizationContext synchronizationContext;
private readonly Action<T>? handler;
private readonly SendOrPostCallback invokeHandlers;
private readonly DispatcherQueue dispatcherQueue;
private readonly Action<T> handler;
public DispatcherQueueProgress(Action<T> handler, SynchronizationContext synchronizationContext)
public DispatcherQueueProgress(Action<T> handler, DispatcherQueue dispatcherQueue)
{
this.synchronizationContext = synchronizationContext;
invokeHandlers = new SendOrPostCallback(InvokeHandlers);
ArgumentNullException.ThrowIfNull(handler);
this.dispatcherQueue = dispatcherQueue;
this.handler = handler;
}
public event EventHandler<T>? ProgressChanged;
public void Report(T value)
{
Action<T>? handler = this.handler;
EventHandler<T>? changedEvent = ProgressChanged;
if (handler is not null || changedEvent is not null)
{
synchronizationContext.Post(invokeHandlers, value);
}
}
[SuppressMessage("", "SH007")]
private void InvokeHandlers(object? state)
{
T value = (T)state!;
Action<T>? handler = this.handler;
EventHandler<T>? changedEvent = ProgressChanged;
handler?.Invoke(value);
changedEvent?.Invoke(this, value);
Action<T> handler = this.handler;
dispatcherQueue.TryEnqueue(() => handler(value));
}
}

View File

@@ -8,8 +8,6 @@ namespace Snap.Hutao.Core.Threading;
/// </summary>
internal interface ITaskContext
{
SynchronizationContext SynchronizationContext { get; }
void BeginInvokeOnMainThread(Action action);
void InvokeOnMainThread(Action action);

View File

@@ -0,0 +1,11 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Dispatching;
namespace Snap.Hutao.Core.Threading;
internal interface ITaskContextUnsafe
{
DispatcherQueue DispatcherQueue { get; }
}

View File

@@ -9,7 +9,7 @@ namespace Snap.Hutao.Core.Threading;
/// 任务上下文
/// </summary>
[Injection(InjectAs.Singleton, typeof(ITaskContext))]
internal sealed class TaskContext : ITaskContext
internal sealed class TaskContext : ITaskContext, ITaskContextUnsafe
{
private readonly DispatcherQueueSynchronizationContext synchronizationContext;
private readonly DispatcherQueue dispatcherQueue;
@@ -24,7 +24,7 @@ internal sealed class TaskContext : ITaskContext
SynchronizationContext.SetSynchronizationContext(synchronizationContext);
}
public SynchronizationContext SynchronizationContext { get => synchronizationContext; }
public DispatcherQueue DispatcherQueue { get => dispatcherQueue; }
/// <inheritdoc/>
public ThreadPoolSwitchOperation SwitchToBackgroundAsync()