作为一个线程初始者,我正在尝试找到一种不需要锁定对象的方法来将任务加入线程池,以使其最大并行度为1。
这段代码能实现我的想法吗?
这段代码能实现我的想法吗?
private int status;
private const int Idle = 0;
private const int Busy = 1;
private void Schedule()
{
// only schedule if we idle
// we become busy and get the old value to compare with
// in an atomic way (?)
if (Interlocked.Exchange(ref status, Busy) == Idle)
{
ThreadPool.QueueUserWorkItem(Run);
}
}
也就是说,以线程安全的方式在状态为 Idle
时将 Run
方法加入队列。
根据我的测试结果,这个方法似乎可以正常工作,但由于这不是我的专业领域,我不能确定。
ConcurrentQueue<T>
中获取任务。 - Roger Johansson