1+ using System ;
2+ using System . Collections . Concurrent ;
3+ using System . Collections . Generic ;
4+ using System . Threading ;
5+ using System . Threading . Tasks ;
6+
7+ namespace ZkData
8+ {
9+ //Priority Scheduler implementation from https://stackoverflow.com/a/9056702/ by Roman Starkov
10+ public class PriorityScheduler : TaskScheduler
11+ {
12+ public static PriorityScheduler AboveNormal = new PriorityScheduler ( ThreadPriority . AboveNormal ) ;
13+ public static PriorityScheduler BelowNormal = new PriorityScheduler ( ThreadPriority . BelowNormal ) ;
14+ public static PriorityScheduler Lowest = new PriorityScheduler ( ThreadPriority . Lowest ) ;
15+
16+ private BlockingCollection < Task > _tasks = new BlockingCollection < Task > ( ) ;
17+ private Thread [ ] _threads ;
18+ private ThreadPriority _priority ;
19+ private readonly int _maximumConcurrencyLevel = Math . Max ( 1 , Environment . ProcessorCount ) ;
20+
21+ public PriorityScheduler ( ThreadPriority priority )
22+ {
23+ _priority = priority ;
24+ }
25+
26+ public override int MaximumConcurrencyLevel
27+ {
28+ get { return _maximumConcurrencyLevel ; }
29+ }
30+
31+ protected override IEnumerable < Task > GetScheduledTasks ( )
32+ {
33+ return _tasks ;
34+ }
35+
36+ protected override void QueueTask ( Task task )
37+ {
38+ _tasks . Add ( task ) ;
39+
40+ if ( _threads == null )
41+ {
42+ _threads = new Thread [ _maximumConcurrencyLevel ] ;
43+ for ( int i = 0 ; i < _threads . Length ; i ++ )
44+ {
45+ int local = i ;
46+ _threads [ i ] = new Thread ( ( ) =>
47+ {
48+ foreach ( Task t in _tasks . GetConsumingEnumerable ( ) )
49+ base . TryExecuteTask ( t ) ;
50+ } ) ;
51+ _threads [ i ] . Name = string . Format ( "PriorityScheduler: " , i ) ;
52+ _threads [ i ] . Priority = _priority ;
53+ _threads [ i ] . IsBackground = true ;
54+ _threads [ i ] . Start ( ) ;
55+ }
56+ }
57+ }
58+
59+ protected override bool TryExecuteTaskInline ( Task task , bool taskWasPreviouslyQueued )
60+ {
61+ return false ; // we might not want to execute task that should schedule as high or low priority inline
62+ }
63+ }
64+ }
0 commit comments