用于单线程执行的.Net标准库

时间:2016-03-21 17:39:48

标签: .net multithreading

我只是手写这段代码:

class SingleWorkerThread
{
    private static readonly ILog _logger = LogManager.GetLogger(typeof(SingleWorkerThread));
    public readonly BlockingCollection<Action> tasks = new BlockingCollection<Action>();
    private readonly Thread thread;

    private void executeThread()
    {
        _logger.InfoFormat("Starting execution");
        Action task;
        while( (task = tasks.Take()) != null)
        {
            _logger.InfoFormat("About to execute a task...", task);
            task();
            _logger.InfoFormat("Completed executing task");
        }
        _logger.InfoFormat("Finished execution");
    }

    public SingleWorkerThread()
    {
        thread = new Thread(executeThread);
    }

    public void Start()
    {
        thread.Start();
    }

    public void Terminate()
    {
        tasks.Add(null);
    }

    public void AddTask(Action a)
    {
        tasks.Add(a);
    }

    public void Join()
    {
        // Wait up to 2 seconds for thread to terminate.
        thread.Join(2000);
    }
}

我正在使用它来确保某个类别的任务的所有执行总是由一个线程完成。

我想避免&#34;重新发明轮子&#34;如果可能的话 - 是否存在标准的.Net&#34;队列消耗线程&#34;我可以使用哪个模块代替上面的那个?

如果没有,是否有任何&#34;陷阱&#34; (即错误),在我刚发布的代码中?

1 个答案:

答案 0 :(得分:0)

我会使用Microsoft的Reactive Framework(NuGet“Rx-Main”)。

这基本上就是代码:

class SingleWorkerThread : IDisposable
{
    private Subject<Action> _subject;
    private IScheduler _scheduler;
    private IDisposable _subscription;

    private static readonly ILog _logger = LogManager.GetLogger(typeof(SingleWorkerThread));

    public SingleWorkerThread()
    {
        _scheduler = new EventLoopScheduler()
        _subject = new Subject<Action>();
        _subscription =
            _subject
                .ObserveOn(_scheduler)
                .Subscribe(task =>
                {
                    _logger.InfoFormat("About to execute a task...", task);
                    task();
                    _logger.InfoFormat("Completed executing task");
                });
    }

    public void Dispose()
    {
        _subscription.Dispose();
    }

    public void AddTask(Action Action)
    {
        _subject.OnNext(Action);
    }
}