我有几个总是正在运行的线程执行“任务”,一个线程获得新的“任务”并在这些线程之间分配。
执行任务的线程:
public class TaskExecutor
{
public object CurrentTask { get; set; }
public Thread ThreadRef { get; set; }
private void Run()
{
while (true)
{
try
{
if (CurrentTask != null)
ExecuteTask(CurrentTask);
else
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException)
{
}
catch (Exception)
{
CurrentTask = null;
}
}
}
private void ExecuteTask(object task)
{
}
}
分配任务的线程:
private void TryDistribute(TaskExecutor thread, object task)
{
if (thread.CurrentTask == null)
{
thread.CurrentTask = task;
thread.ThreadRef.Interrupt();
}
}
如何使用TPL任务实现相同的逻辑(无限期等待和唤醒其他线程的处理)?