Reputation: 5211
In the example below only _DisplayUsingThreads(timesToDisplay) truly do operation in parallel. While the other two _DisplayUsingTasks and _DisplayUsingDelegates only do 4 at a time (on a quad core machine) and then wait for a second before doing 4 more. Why?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
delegate void DisplayDelegate();
DisplayDelegate myDisplaySleep;
private void btnGo_Click(object sender, EventArgs e)
{
const int timesToDisplay = 50;
//_DisplayUsingDelegates(timesToDisplay);
//_DisplayUsingTasks(timesToDisplay);
//_DisplayUsingThreads(timesToDisplay);
}
private void _DisplayUsingTasks(int displayNumber)
{
for (int i = 0; i < displayNumber; i++)
{
Task task = new Task(DisplayIdSleep);
task.Start();
}
}
private void _DisplayUsingThreads(int displayNumber)
{
for (int i = 0; i < displayNumber; i++)
{
Thread thread = new Thread(DisplayIdSleep);
thread.Start();
}
}
private void _DisplayUsingDelegates(int displayNumber)
{
myDisplaySleep = DisplayIdSleep;
for (int i = 0; i < displayNumber; i++)
{
myDisplaySleep.BeginInvoke(null, null);
}
}
private void DisplayIdSleep()
{
Debug.WriteLine("Thread Id : {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
}
}
Upvotes: 3
Views: 580
Reputation: 10226
The number of operations that can be queued to the thread pool is limited only by available memory; however, the thread pool limits the number of threads that can be active in the process simultaneously. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space.
Upvotes: 0
Reputation: 3785
This is a result of Task
and BeginInvoke
using thread pool threads, whereas creating your own thread, well, creates a thread.
Add ThreadPool.SetMinThreads(50, 0);
to btnGo_Click
and observe what happens.
Upvotes: 4