Does Thread.Sleep affect the ThreadPool?

2020-07-22 04:26发布

问题:

I need to control one thread for my own purposes: calculating, waiting, reporting, etc...
In all other cases I'm using the ThreadPool or TaskEx.

In debugger, when I'm doing Thread.Sleep(), I notice that some parts of the UI are becoming less responsible. Though, without debugger seems to work fine.

The question is: If I'm creating new Thread and Sleep()'ing it, can it affect ThreadPool/Tasks?

EDIT: here are code samples:

One random place in my app:

ThreadPool.QueueUserWorkItem((state) =>
{
    LoadImageSource(imageUri, imageSourceRef);
});

Another random place in my app:

var parsedResult = await TaskEx.Run(() => JsonConvert.DeserializeObject<PocoProductItem>(resultString, Constants.JsonSerializerSettings));

My ConcurrentQueue (modified, original is taken from here):

Creation of thread for Queue needs:

public void Process(T request, bool Async = true, bool isRecurssive = false)
{
    if (processThread == null || !processThread.IsAlive)
    {
        processThread = new Thread(ProcessQueue);
        processThread.Name = "Process thread @ " + Environment.TickCount;
        processThread.Start();
    }

If one of the Tasks reports some networking problems, i want this thread to wait a bit

if (ProcessRequest(requestToProcess, true))
{
    RequestQueue.Dequeue();
}
else
{
    DoWhenTaskReturnedFalse();
    Thread.Sleep(3000);
}

So, the question one more time: can Thread.Sleep(3000);, called from new Thread(ProcessQueue);, affect ThreadPool or TaskEx.Run() ?

回答1:

Assuming that the thread you put on sleep was obtained from thread pool then surely it does affect the thread pool. If you explicitly say that the thread should sleep then it cannot be reused by the thread pool during this time. This may cause the thread pool to spawn new threads if there are some jobs awaiting to be scheduled. Creating a new thread is always expensive - threads are system resources.

You can however look at Task.Delay method (along with async and await) that suspends executing code in a more intelligent way - allowing the thread to be reused during waiting. Refer to this Thread.Sleep vs. Task.Delay article.



回答2:

Thread.Sleep() affects the thread it's called from, if you're calling Thread.Sleep() in a ThreadPool thread and trying to queue up more it may be hitting the max count of ThreadPool threads and waiting for a thread to finish before executing another.

http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads.aspx



回答3:

No, the Thread.Sleep() is only on the current thread. Thread.Sleep(int32) documentation:

The number of milliseconds for which the thread is suspended.