Sclrx
Sclrx

Reputation: 151

If a task gets locked, does it go back to the queue, or does it lock the thread too?

I was wondering how good tasks are for scenarios where the main issue is resource locking (think COM port access, for example).

If my task is this :

    Task
    {
        lock(resource)
        {
            resource.doSomething();
        }
    };

What it essentially does, is wait until the resource is free, and then use it.

My question is this : if the resource is locked, does the task go back to the task queue, or is the thread locked until the resource is free?

My understanding is that if the task is locked, in this scenario, it would be better to use a thread to avoid filling the thread pool with locked threads, is it right?

Upvotes: 1

Views: 643

Answers (2)

Theodor Zoulias
Theodor Zoulias

Reputation: 43515

The current implementation of the System.Threading.ThreadPool class when starved spawns a new thread every 500 msec. This could create latency if you are using many thread-pool threads in a blocking manner. It is possible though to boost the initial reserve of threads in the ThreadPool by using the method SetMinThreads. Each thread consumes around 1MB of memory, so in that case you'll be trading memory for performance.

int workerThreads, completionPortThreads; // Get the current settings
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(100, completionPortThreads);

You probably don't want to change the size of the completion port threads pool (threads handling the completion of IO requests). So you can get the current size by using the GetMinThreads method, and then use it in the SetMinThreads to preserve the default.

Upvotes: 0

Farhad Rahmanifard
Farhad Rahmanifard

Reputation: 688

Your assumption is right. The task waits until the resource gets free and then continues its execution.
You can define the task as LongRunning one, so the system handles it more appropriate. Also, you can run a thread if you want for any reason but consider that a locked thread does not consume much CPU resource, and the ThreadPool handles the adequate number of active threads itself. If you are not going to run many many tasks(say more than 1000), do not worry about it.

Upvotes: 1

Related Questions