Answer the question
In order to leave comments, you need to log in
Task vs ThreadPool vs new Thread?
The task is to process 100+ long-term operations (let's say each takes 10 seconds). It is natural to process it is necessary asynchronously, all at the same time. Well, 100 pieces have been processed and a million more are on the way, if anything ...
So, how to do it more correctly and more quickly?
Limitation: .NET Framework 4.0
for (int i = 0; i < 100; i++) {
int j = i;
Task t = new Task(() => {
Console.WriteLine("RUN "+j);
Thread.Sleep(10000);
Console.WriteLine("end " + j);
});
t.Start();
//ИЛИ
ThreadPool.QueueUserWorkItem(state => {
Console.WriteLine("RUN " + j);
Thread.Sleep(10000);
Console.WriteLine("end " + j);
});
//ИЛИ
Thread t = new Thread(() =>
{
Console.WriteLine("RUN " + j);
Thread.Sleep(10000);
Console.WriteLine("end " + j);
});
t.Start();
}
ThreadPool.SetMaxThreads(100, 100);
Answer the question
In order to leave comments, you need to log in
1) Look, if you have asynchronous work (you write work with sockets), then it is not advisable to create many threads, since a thread implies the work of a processor, and when working with sockets, this thread will be idle most of the time.
2) Tasks use a thread pool, so there is not much difference between ThreadPool.QueueUserWorkItem and Task launch.
3) What is Thread.Sleep(10000) and Task.Delay(10000).Wait() is a blocking operation that results in what is called thread pool starvation. That is, the thread does not have the opportunity to return to the pool and be reused. The thread pool has a delay in putting a new thread into operation, so everything slows down for you.
The conclusion is that you are incorrectly preparing async. In all cases, you block threads and the number of threads you have is approximately the same in all cases. If you're limited to 4.0 then the old .net async model is likely the best option
https://docs.microsoft.com/en-us/dotnet/standard/a...
Sockets have corresponding methods
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question