This blog is subject the DISCLAIMER below.

Saturday, July 21, 2007

Threading

This post for novice C# programmers..

Did you hear about Threading?

If not, let’s read these lines as a brief introduction about threading.

Thread is a tunnel between machine processor and your application. An entire application may contain more than one thread, and thread just owned by one application.Processor communicates with your application or in another manner does some processes needed by your application via main thread if you didn’t create a one by your hand, one thread and processor(s) == one process at time and the problem is here.

Sometimes you need to draw something, say dozens of lines using GDI+ on you form and do something on that time and ….. if you did everything right, let’s press F5, I can tell you what’d happen, your application would be in “Not responding” state until your Draw method exited. After that you’ll see your lines and your application run normally but sure that’s wrong.

So, what happened there were two processes processor did, the first Update method is one used to update application form and the second was Draw to draw the lines, once any change done on the form an event raised to redraw the form using Update method.

So, the solution is very clear is to create another thread; it controls the paint operation and this is good and works well till now.

So, the question is How to create another thread?!!

Just use System.Threading;

Let’s say we are going to draw the lines when the user press button “Start drawing”So in drawBtn click event handler we write this piece of code:

System.Threading.ThreadStart thrdStart = new System.Threading.ThreadStart(Draw);
System.Threading.Thread thrd = new System.Threading.Thread(thrdStart);
thrd.Start();

Sample draw method would be

To download the demo

To be continued…