Stress testin with Asynchronously Calling 100 thread
I just want to Call 100 thread asynchronously with C#(you can think each thread one user) and I want to get serialization time a开发者_StackOverflowvarage of my code.Should I use Thread Pool for this? Thx
I just want to Call 100 thread asynchronously
What do you exactly mean?
If you need to execute 100 tasks asynchronously -ThreadPool is the best solution. You don't care about threads, just queue work items into pool, and operating system split items amongst available threads. You should realize that all your 100 tasks could be processed just with 3 or 5(for example) threads.
If you need to create 100 threads and delegate each task to separate thread - ThreadPool isn't solution, because ThreadPool doesn't create new threads. You should create them manually.
// Create 100 threads
var threads = new List<Thread>();
for (int p = 0; p < 100; p++)
{
threads.Add(new Thread(() => MyTask()));
}
// Start them all
foreach (var thread in threads)
{
thread.Start();
}
// Wait for completion
foreach (var thread in threads)
{
thread.Join();
}
You definitely can use ThreadPool for your task, but you should be aware of how ThreadPool
manages threads. If you try to start 100 threads in a way like this:
for (int i = 0; i < 100; i++)
{
ThreaPool.QueueUserWorkItem(state => UnitOfWork());
}
then there is no any guaranty that all 100 threads will execute in separate threads simultaneously. ThreadPool queues tasks, and execute them using free threads in ThreadPool, hence it can queue all your tasks one after another and execute them one after another. I don't say that it will do so, but hypothetically it can be.
But I think you shouldn't bother about it. Try to use ThreadPool first, set max treads limit to 100 (or above) with ThreadPool.SetMaxThreads(100) and queue requests as I wrote above.
And if after that you would like something more complicated you can use the Thread class. Create 100 instances of the Thread
class, start them all and use. If you would use Thread
class you can control lifetime of each thread, i.e. wait for threads completion without using any additional tricks.
If you set MaxThreads to 100 and more, it is probably the best solution.
ThreadPool.SetMaxThreads(100)
精彩评论