使用TPL任务调度程序执行长任务

时间:2016-12-21 15:02:40

标签: c# .net multithreading task-parallel-library observer-pattern

我正在使用一个数据流源,它在间隔> = 5秒内推送数据。我有一个像下面这样的观察者接收推送通知:

public class ConsoleDataObserver : IObserver<DataPipeEvent>
    {
        private DataPipeType _dataPipeType;
        private LimitedConcurrencyLevelTaskScheduler _scheduler;//This is based on msdn parallel extensions examples
        private TaskFactory _factory;


        public ConsoleDataObserver(DataPipeType afDataPipeType)
        {
            _dataPipeType = afDataPipeType;
            _scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
            _factory = new TaskFactory(_scheduler);
        }


        public void OnNext(DataPipeEvent dataPipeEvent)
        {
            _factory.StartNew(() => ProcessDataNow(dataPipeEvent));
        }

        private void ProcessDataNow(DataPipeEvent dataPipeEvent)
        {
            Thread.Sleep(8000); //just want to simulate long running tasks

        }

        public void OnError(Exception error)
        {
            Console.WriteLine("Provider has sent an error");
        }

        public void OnCompleted()
        {
            Console.WriteLine("Provider has terminated sending data");
        }
    }

我有以下要求:

在我的OnNext中,我不想阻止主线程,并希望在其他线程中执行长时间运行的处理任务。我正在使用TaskScheduler来使用ThreadPool。这是好的实施吗? OnNext每秒可以获得500-1000个事件。 ProcessDataNow将记录任何异常。

0 个答案:

没有答案