Task.Factory.StartNew()将线程返回给线程池

时间:2018-04-06 19:06:55

标签: c# multithreading task-parallel-library

在此实现中,Task.Factory.StartNew永远不会将线程返回到线程池,因为它包含与Thread.Sleep的while(true)。这样对吗?如何检查queue它是否有需要完成的任务?

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Helper h = new Helper();
        PlayWithQueue s = new PlayWithQueue();
        s.AddToQueueForExecution(() => { h.Indicate(1); });
        s.AddToQueueForExecution(() => { h.Indicate(2); });
        s.AddToQueueForExecution(() => { h.Indicate(3); });
        s.AddToQueueForExecution(() => { h.Indicate(4); });
        s.AddToQueueForExecution(() => { h.Indicate(5); });
        s.AddToQueueForExecution(() => { h.Indicate(6); });

        Console.ReadKey();
    }
}
public class PlayWithQueue
{
    private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

    public PlayWithQueue()
    {
        var task = Task.Factory.StartNew(ThreadProc);
    }

    public void AddToQueueForExecution(Action action)
    {
        queue.Enqueue(action);
    }
    private void ThreadProc()
    {
        while (true)
        {
            Action item;
            bool isSuccessfull = false;
            isSuccessfull = queue.TryDequeue(out item);
            if (isSuccessfull)
            {
                item();
            }
            System.Threading.Thread.Sleep(100);
        }
    }
}
public class Helper
{
    public void Indicate(int number)
    {
        Random rnd = new Random();
        int timeDelay = rnd.Next(1000, 5000);
        Console.WriteLine("Start" + number.ToString());
        System.Threading.Thread.Sleep(timeDelay);
        Console.WriteLine("End" + number.ToString() + " " + timeDelay.ToString());
    }
}
}

2 个答案:

答案 0 :(得分:-1)

ThreadProc方法更改为此。循环直到队列有一个项目。

private void ThreadProc()
    {
        Action item;
        while (queue.TryDequeue(out item))
        {
            item();
            System.Threading.Thread.Sleep(100);
        }
    }

答案 1 :(得分:-1)

好的,暂时还没有编写任何C#,但这里是你不能阻止线程的方法

private async void ThreadProc()
    {
        while (true)
        {
            Action item;
            bool isSuccessfull = false;
            isSuccessfull = queue.TryDequeue(out item);
            if (isSuccessfull)
            {
                item();
            }
            await Task.Delay(300);
        }
    }

但也许如果我要实现这个,我会直接在AddToQueueForExecution中运行操作,而不是在另一个线程上排队...如果你想要这个thread safe,即没有2个动作同时运行 - 只需使用锁。