等待未知数量的任务,然后阻止任何新任务

时间:2014-02-25 04:24:31

标签: .net multithreading

什么是.NET中最好的同步原语/模式,等待未知数量的线程/任务完成,然后立即阻止任何新的线程/任务执行?

基本上类似于AddWaitForAllThenDispose的任务集合。 WaitForAllThenDispose允许在等待期间添加新任务并正确等待所有任务。

但是,只要所有活动任务都完成且没有对Add的并发调用,它就会移动到dispose并阻止添加任何新任务。

1 个答案:

答案 0 :(得分:0)

模式我现在结束了:

public class ActionScheduler {
    private readonly CountdownEvent _allCompleted = new CountdownEvent(1);
    private volatile bool _disposed;

    public void Schedule(Action action) {
        if (_disposed)
            throw new ObjectDisposedException("ActionScheduler");

        // this feels ugly:
        try {
            _allCompleted.AddCount();
        }
        catch (InvalidOperationException) {
            // should only happen after the dispose/wait has completed
            throw new ObjectDisposedException("ActionScheduler");
        }

        ScheduleInternal(() => {
            try {
                action();
            }
            finally {
                _allCompleted.Signal();
            }
        });
    }

    private void ScheduleInternal(Action action) {
        // some async scheduling irrelevant to the example
    }

    public void Dispose() {
        if (_disposed)
            return;

        _allCompleted.Signal(); // removing initial +1
        _allCompleted.Wait();
        _disposed = true;
    }
}