CST1620 C# / C++ Programming
Lab Week 10


Articles on multithreading.  Keep in mind that multithreading works differently in .NET 2003 and .NET2005

http://msdn.microsoft.com/msdnmag/issues/03/02/Multithreading/default.aspx

http://msdn2.microsoft.com/en-us/library/ms171728.aspx

 

Here is one way to create threads so you don't get exceptions:

// create a delegate function as follows

delegate doSomething(String txt);

// Create a method that will be called for doing the updates

private void DoSomething(String txt)
{
    // Check if an Invoke is required
    if (InvokeRequired) {
        // This will run when a thread other than the main thread is calling this method
        Invoke( new doSomething(DoSomething), new object[] {txt});
    } else {
        // Just modify object directly if its called from main thread
        Do whatever you want to do to the control
    }
}

private void ButtonClick()
{
    Thread newThread = new Thread(new ThreadStart(ThreadProcess));
    newThread.Start();
}

private void ThreadProcess()
{
    // Do something lengthy here that involves calling DoSomething method
}


This is s not actual compilable code but it lays out the things needed for multi-threaded action.

 

 

Exercises

Exercise 14.1  Multithreading (10 points)

In this exercise your are going to build upon Exercise 5.6 that you completed several weeks ago.

Basically you are to duplicate the Pythagorean Triples program logic 3 times (or more).  Run each duplication of the logic as a separate thread.  Review my example programs  to get a better understanding of the problem.

Write a main Windows GUI program (Ex14_1) to test your multithreading.

Use the Windows Task Manager to see the effectiveness of your multithreading.  If your application is written correctly, your program should have a CPU usage of at least 80%, but probably not more than 95%.

  Result (Save to your local machine and run)  This is the program before it is multithreaded.  It uses the DoEvents method to help responsiveness.  However this solution is not as responsive as it should be.  Also the programmer has no control over the wait period.

  Result (Save to your local machine and run)  This is the program written using multithreading.  The programmer has the ability to control processor loading and overall responsiveness is increased.

Note:
At first it appeared that if I clicked start button many times in succession for a set of program logic, that the threads were interfering with each other.  You would see unusual results in the list box.  But on further examination, the threads are running independently just fine.  The list box is just being written to by multiple threads executing at the same time.