Tell me what is the correct way to start the multithreaded execution of the method, I need to start the execution of the method (program) in 100 threads. For example, I need to take proxies from the list and check for a 200 response.
How to properly run the program in 100 threads?
//Array Threads
for (int j = 0; j < 100; j++)
{
arrThread[j] = new Thread(new ThreadStart(new Worck().SearchUrls));
arrThread[j].IsBackground = true;
arrThread[j].Start();
}
//Array Tasks
for (int j = 0; j < 100; j++)
{
arrTask[j] = new Task(new Worck().SearchUrls);
arrTask[j].Start();
}
//Task
await Task.Run(() =>
{
for (int j = 0; j < 100; j++)
{
new Task(() => new Worck().SearchUrls()).Start();
}
});
//Parallel
await Task.Run(() =>
{
Parallel.For(1, 100, new Worck().SearchUrls());
});
How to properly run the program in 100 threads?
I generally recommend using the highest-level API that is available.
In this case, Parallel.For
is the highest-level API. The Parallel
type splits its work into Task
s, which are distributed among threads in the thread pool.
Manually creating Thread
objects should be extremely rare; these days it's only necessary if you're doing things like COM interop. Manually creating Task
objects via the Task
constructor should never be done .
For example, I need to take proxies from the list and check for a 200 response.
In this case, the question is wrong. You don't need 100 threads to do that. Or any explicit threads, for that matter.
Since the operation is I/O-bound, what you want is an asynchronous solution. First, write a properly-asynchronous SearchUrlsAsync
(eg, by making asynchronous network calls). Then, you can start all the asynchronous operations and then asynchronously wait for them all to complete:
var tasks = Enumerable.Range(0, 100).Select(_ => new Worck().SearchUrlsAsync()).ToList();
await Task.WhenAll(tasks);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.