唤醒任务无限期地像Thread.Interrupt一样睡觉

时间:2017-05-26 18:08:08

标签: c# .net multithreading task-parallel-library

我有几个总是正在运行的线程执行“任务”,一个线程获得新的“任务”并在这些线程之间分配。

执行任务的线程:

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任务实现相同的逻辑(无限期等待和唤醒其他线程的处理)?

0 个答案:

没有答案