the main reason that I've started to play with threads is because the industry WILL (sooner or later) move to a multi-core guided programing, and it WILL become mainstream (mark my words :) ).
any way, lets start from the beginning, and why do we need threads.
according to the definition : "Threads are a way for a program to split itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another, but in general, the way that a thread is created and shares its resources is different from the way a process does."
so, in other words, we will use threads when we need to perform simultaneous tasks.
these kind of actions made when you have unused processing time while waiting for other task to finish.
so, back to the .Net world, how would we do that ?
to use threads, we need to include the library :
using System.Threading;
the next thing we need i to know how to to lunch a thread with a task.
- we need to create a task to be done.
- a ThredStart delegate which will point to our task.
- a new thread ( or an old one from a thread pool ) - which is better and when will be explained in some later posts.
- start the thread.
so :
lets create some task :
private void BurnCPUwithOneThread()
{
for(int i=0; i< 5000000;i++)
{
lblcounter.Text = i.ToString();
}
}
and one more :
private void BurnCPUwithTwoThreads()
{
for(int i=0; i< 5000000;i++)
{
lblCounter2.Text = i.ToString();
}
}
now we will create the delegate and the threads, and activate them.
private void button4_Click(object sender, System.EventArgs e)
{
//We will run the action in a different thread from the gui
//so when we do sleep the the tread the gui will not hang up.
// Create the thread start object
ThreadStart ts = new ThreadStart(BurnCPUwithOneThread);
// The tread itself
Thread t = new Thread(ts);
// Starting the thread
t.Start();
// Create the thread start object
ThreadStart ts2 = new ThreadStart(BurnCPUwithTwoThreads);
// The tread itself
Thread t2 = new Thread(ts2);
// Starting the thread
t2.Start();
}
thats it.
now you have a working little program with 2 threads.
if you will run this code , you will notice that it is done simultaneously.
next lessons will handle : sending parameters to threads, synchronizing, thread pool, and more.
please comment, if you would like me to focus on some specific subject...