我想实现一个有优先级的
我阅读了 Parallel Extensions Extras Samples 和 Guide to Implementing Custom TPL Dataflow Blocks,但仍然不清楚如何实现这种情况。
---------------------------- 编辑 ---------------------------
有一些任务,其中5个可以同时运行。当用户按下按钮时,根据谓词函数,应该以最高优先级运行一些任务。
实际上,我写了这段代码。
ActionBlock<T>
,这样我就可以通过使用 Predicate<T>
条件性地给一些 TInput
项目设置优先级。我阅读了 Parallel Extensions Extras Samples 和 Guide to Implementing Custom TPL Dataflow Blocks,但仍然不清楚如何实现这种情况。
---------------------------- 编辑 ---------------------------
有一些任务,其中5个可以同时运行。当用户按下按钮时,根据谓词函数,应该以最高优先级运行一些任务。
实际上,我写了这段代码。
TaskScheduler taskSchedulerHighPriority;
ActionBlock<CustomObject> actionBlockLow;
ActionBlock<CustomObject> actionBlockHigh;
...
queuedTaskScheduler = new QueuedTaskScheduler(TaskScheduler.Default, 5);
taskSchedulerHigh = queuedTaskScheduler.ActivateNewQueue(0);
taskSchedulerLow = queuedTaskScheduler.ActivateNewQueue(1);
...
actionBlockHigh = new ActionBlock<CustomObject>(new Action<CustomObject>(method), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, SingleProducerConstrained = false, TaskScheduler = taskSchedulerHigh });
actionBlockLow = new ActionBlock<CustomObject>(new Action<CustomObject>(method), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, MaxMessagesPerTask = 1, TaskScheduler = taskSchedulerLow });
...
if (predicate(customObject))
actionBlockHigh.Post(customObject);
else
actionBlockLow.Post(customObject);
但是似乎优先级根本没有生效。
---------------------------- 编辑 ------------------
我发现当我使用这行代码时:
actionBlockHigh = new ActionBlock<AvlHistory>(new Action<AvlHistory>(SemaphoreAction), new ExecutionDataflowBlockOptions { TaskScheduler = taskSchedulerHigh });
actionBlockLow = new ActionBlock<AvlHistory>(new Action<AvlHistory>(SemaphoreAction), new ExecutionDataflowBlockOptions { TaskScheduler = taskSchedulerLow });
应用程序正确地观察任务的优先级,但一次只能执行一个任务。同时,使用以下代码块,应用程序可以同时运行5个任务,但优先级顺序不合适。
actionBlockHigh = new ActionBlock<AvlHistory>(new Action<AvlHistory>(SemaphoreAction), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, TaskScheduler = taskSchedulerHigh });
actionBlockLow = new ActionBlock<AvlHistory>(new Action<AvlHistory>(SemaphoreAction), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, TaskScheduler = taskSchedulerLow });
更新:
感谢svick的提示,我应该为taskSchedulerLow
指定MaxMessagesPerTask
。
T
没有关系?还是优先级是T
的固有/派生属性? - casperOne