我想獲得當前正在執行的任務,我正在添加在阻塞隊列中,它是如何完成的?如何在C#的阻塞隊列中獲取當前正在運行的任務?
編輯:我使用這個優先級調度,並加入多任務不同的優先級:
public class PriorityScheduler : TaskScheduler
{
public static PriorityScheduler Highest = new PriorityScheduler(ThreadPriority.Highest);
public static PriorityScheduler AboveNormal = new PriorityScheduler(ThreadPriority.AboveNormal);
public static PriorityScheduler Normal = new PriorityScheduler(ThreadPriority.Normal);
public static PriorityScheduler BelowNormal = new PriorityScheduler(ThreadPriority.BelowNormal);
public static PriorityScheduler Lowest = new PriorityScheduler(ThreadPriority.Lowest);
public static BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
private Thread[] _threads;
private ThreadPriority _priority;
private readonly int _maximumConcurrencyLevel = Math.Max(1, Environment.ProcessorCount);
public PriorityScheduler(ThreadPriority priority)
{
_priority = priority;
}
public override int MaximumConcurrencyLevel
{
get { return _maximumConcurrencyLevel; }
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return _tasks;
}
protected override void QueueTask(Task task)
{
_tasks.Add(task);
if (_threads == null)
{
_threads = new Thread[_maximumConcurrencyLevel];
for (int i = 0; i < _threads.Length; i++)
{
int local = i;
_threads[i] = new Thread(() =>
{
foreach (Task t in _tasks.GetConsumingEnumerable())
base.TryExecuteTask(t);
});
_threads[i].Name = string.Format("PriorityScheduler: ", i);
_threads[i].Priority = _priority;
_threads[i].IsBackground = true;
_threads[i].Start();
}
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false; // we might not want to execute task that should schedule as high or low priority inline
}
}
我想停下來,這取決於有優先級,例如恢復任務如果具有較高優先級,新任務到達,下停止,讓任務執行,然後繼續自己...
你能提供意見,以要「得到當前正在執行的任務」短代碼的例子嗎? –
您期望如何停止正在運行的任務? – svick
我的意思是取消一個正在運行的任務....然後用相同的憑證重新啓動它......如果有一種優雅的方式,請分享它嗎? – faizanjehangir