IProgress<T> synchronization

本文关键字:synchronization gt IProgress lt | 更新日期: 2023-09-27 18:25:48

我在C#中有以下内容

public static void Main()
{
    var result = Foo(new Progress<int>(i =>
        Console.WriteLine("Progress: " + i)));
    Console.WriteLine("Result: " + result);            
    Console.ReadLine();
}
static int Foo(IProgress<int> progress)
{
    for (int i = 0; i < 10; i++)
        progress.Report(i);
    return 1001;
}

Main的一些输出是:

首次运行:

Result: 1001
Progress: 4
Progress: 6
Progress: 7
Progress: 8
Progress: 9
Progress: 3
Progress: 0
Progress: 1
Progress: 5
Progress: 2

第二次运行:

Progress: 4
Progress: 5
Progress: 6
Progress: 7
Progress: 8
Progress: 9
Progress: 0
Progress: 1
Progress: 2
Result: 1001
Progress: 3

等等。。。

每次运行的输出都不同。如何同步这些方法,以便按报告的顺序显示进度0,1,。。。9之后是1001的结果。我希望输出是这样的:

Progress: 0
.
.
.
Progress: 9
Result: 1001

IProgress<T> synchronization

进度<>类使用SynchronizationContext.Current属性来发布()进度更新。这样做是为了确保ProgressChanged事件在程序的UI线程上触发,从而可以安全地更新UI。需要安全地更新ProgressBar.Value属性。

控制台模式应用程序的问题是它没有同步提供程序。不像Winforms或WPF应用程序。Current属性具有默认提供程序,其Post()方法在线程池线程上运行。在没有任何联锁的情况下,哪个TP线程首先报告其更新是完全不可预测的。也没有任何好的联锁方法。

只是不要在这里使用Progress类,没有任何意义。控制台模式应用程序中没有UI线程安全问题,控制台类已经是线程安全的。修复:

static int Foo()
{
    for (int i = 0; i < 10; i++)
        Console.WriteLine("Progress: {0}", i);
    return 1001;
}

正如Hans的回答中所说,Progress<T>的.NET实现使用SynchronizationContext.Post来发送请求。你可以像伊夫的回答一样直接报告,也可以使用SynchronizationContext.Send,这样请求就会被阻止,直到接收器处理完为止。

由于引用源是可用的,实现它就像复制源并将Post更改为Send以及将SynchronizationContext.CurrentNoFlow更改为SynchronizationContext.Current一样简单,因为CurrentNoFlow是内部属性。

/// <summary>
/// Provides an IProgress{T} that invokes callbacks for each reported progress value.
/// </summary>
/// <typeparam name="T">Specifies the type of the progress report value.</typeparam>
/// <remarks>
/// Any handler provided to the constructor or event handlers registered with
/// the <see cref="ProgressChanged"/> event are invoked through a 
/// <see cref="System.Threading.SynchronizationContext"/> instance captured
/// when the instance is constructed.  If there is no current SynchronizationContext
/// at the time of construction, the callbacks will be invoked on the ThreadPool.
/// </remarks>
public class SynchronousProgress<T> : IProgress<T>
{
    /// <summary>The synchronization context captured upon construction.  This will never be null.</summary>
    private readonly SynchronizationContext m_synchronizationContext;
    /// <summary>The handler specified to the constructor.  This may be null.</summary>
    private readonly Action<T> m_handler;
    /// <summary>A cached delegate used to post invocation to the synchronization context.</summary>
    private readonly SendOrPostCallback m_invokeHandlers;
    /// <summary>Initializes the <see cref="Progress{T}"/>.</summary>
    public SynchronousProgress()
    {
        // Capture the current synchronization context.  "current" is determined by Current.
        // If there is no current context, we use a default instance targeting the ThreadPool.
        m_synchronizationContext = SynchronizationContext.Current ?? ProgressStatics.DefaultContext;
        Contract.Assert(m_synchronizationContext != null);
        m_invokeHandlers = new SendOrPostCallback(InvokeHandlers);
    }
    /// <summary>Initializes the <see cref="Progress{T}"/> with the specified callback.</summary>
    /// <param name="handler">
    /// A handler to invoke for each reported progress value.  This handler will be invoked
    /// in addition to any delegates registered with the <see cref="ProgressChanged"/> event.
    /// Depending on the <see cref="System.Threading.SynchronizationContext"/> instance captured by 
    /// the <see cref="Progress"/> at construction, it's possible that this handler instance
    /// could be invoked concurrently with itself.
    /// </param>
    /// <exception cref="System.ArgumentNullException">The <paramref name="handler"/> is null (Nothing in Visual Basic).</exception>
    public SynchronousProgress(Action<T> handler) : this()
    {
        if (handler == null) throw new ArgumentNullException("handler");
        m_handler = handler;
    }
    /// <summary>Raised for each reported progress value.</summary>
    /// <remarks>
    /// Handlers registered with this event will be invoked on the 
    /// <see cref="System.Threading.SynchronizationContext"/> captured when the instance was constructed.
    /// </remarks>
    public event EventHandler<T> ProgressChanged;
    /// <summary>Reports a progress change.</summary>
    /// <param name="value">The value of the updated progress.</param>
    protected virtual void OnReport(T value)
    {
        // If there's no handler, don't bother going through the [....] context.
        // Inside the callback, we'll need to check again, in case 
        // an event handler is removed between now and then.
        Action<T> handler = m_handler;
        EventHandler<T> changedEvent = ProgressChanged;
        if (handler != null || changedEvent != null)
        {
            // Post the processing to the [....] context.
            // (If T is a value type, it will get boxed here.)
            m_synchronizationContext.Send(m_invokeHandlers, value);
        }
    }
    /// <summary>Reports a progress change.</summary>
    /// <param name="value">The value of the updated progress.</param>
    void IProgress<T>.Report(T value) { OnReport(value); }
    /// <summary>Invokes the action and event callbacks.</summary>
    /// <param name="state">The progress value.</param>
    private void InvokeHandlers(object state)
    {
        T value = (T)state;
        Action<T> handler = m_handler;
        EventHandler<T> changedEvent = ProgressChanged;
        if (handler != null) handler(value);
        if (changedEvent != null) changedEvent(this, value);
    }
}
/// <summary>Holds static values for <see cref="Progress{T}"/>.</summary>
/// <remarks>This avoids one static instance per type T.</remarks>
internal static class ProgressStatics
{
    /// <summary>A default synchronization context that targets the ThreadPool.</summary>
    internal static readonly SynchronizationContext DefaultContext = new SynchronizationContext();
}

正如其他答案之前多次指出的那样,这是由于Progress<T>的实现方式。您可以为您的客户端(库的用户)提供示例代码,或者为控制台项目提供IProgress<T>的实现。这是基本的,但应该做。

public class ConsoleProgress<T> : IProgress<T>
{
    private Action<T> _action;
    public ConsoleProgress(Action<T> action) {
        if(action == null) {
            throw new ArgumentNullException(nameof(action));
        }
        _action = action;
    }
    public void Report(T value) {
        _action(value);
    }
}

这是如何编写Progress<T>的线程问题。您需要编写自己的IProgress<T>实现来获得所需内容。

然而,这个场景已经告诉了你一些重要的事情,尽管在这个例子中,你只是在做简单的Console.Writeline语句,但在真实的场景中,由于需要更长或更短的时间,一些报告可能会以其他顺序报告,所以我认为你无论如何都不应该依赖于该顺序。