Solved

Multi Threading and forms

Posted on 2006-06-19
4
224 Views
Last Modified: 2010-04-16
Hi Experts,

     I have a form with a text box and a command button.  When the user presses the command button, I want to create two seperate instances of the same class and have them run on a thread of there own.  The threads will each come up with a random number between 1 and 10.  When the threads are done I want the form to take the two randomly generated numbers, add them up, and display the added value in the text box.

Something like this:

Form1.cs:
namespace MyNameSpace
{
           Public Partial Class MyForm : Form
           {
                      MyClass class1 = new MyClass;
                      MyClass class2 = new MyClass;
                     
                      class1.StartThread();
                      class2.StartThread();
           

                      Public void AddThem()
                      {
                                  txtBox.Text=class1.Result+class2.Result;
                      }

           }
}

MyClass.cs:
namespace MyNameSpace
{
           public class MyClass
           {
                      int RandNum;
                     
                      public int Result
                      {
                                 get
                                 {
                                              return RandNum;
                                  }
                                  set
                                  {
                                   }
                       }

                      public void StartThread()
                      {
                                 Thread t = new Thread(new ThreadStart(ThreadJob));
                                 t.IsBackground = true;
                                 t.Start();
                       }

                       private void ThreadJob()
                      {
                                 RandNum=GetRandomNum();
                                 myForm.AddThem();
                       }
}

What I am basically having problems with is how to call a function that only exists in the form's code from the class threads.  I know that in my example I could have a zero value for Class1.Result or Class2.Result depending on which thread finished first, but I am not worried about that for now.  I need the classes to be on their own threads so that the GUI is still functioning while my classes are coming up with the random numbers.  I know that in this example I wouldn't need to use mutliple threads, but this is just an example.  In reality ThreadJob takes about 30 seconds to execute.

Any help would be appreciated,

Thanks,
axnst2
0
Comment
Question by:axnst2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 

Author Comment

by:axnst2
ID: 16934914
Please also let me know if you think that I am just going about doing this completely the wrong way.

Thanks.
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 500 total points
ID: 16935137
   public partial class Form1 : Form
    {
        MyClass class1;
        MyClass class2;

        public Form1()
        {
            InitializeComponent();

            class1 = new MyClass();
            class1.OnResultHandler += new ResultHandler(class_OnResultHandler);

            class2 = new MyClass();
            class2.OnResultHandler += new ResultHandler(class_OnResultHandler);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            class1.StartThread();
            class2.StartThread();
        }

        void class_OnResultHandler(int result)
        {
            this.Invoke(new ResultHandler(this.HandleResult), new object[] { result });
        }

        void HandleResult(int result)
        {
            int n = 0;

            try
            {
                n = Int32.Parse(textBox1.Text);
            }
            catch (Exception)
            {
            }

            n += result;

            textBox1.Text = n.ToString();
        }
    }

    public delegate void ResultHandler(int result);

    public class MyClass
    {
        public event ResultHandler OnResultHandler;

        int RandNum;

        public void StartThread()
        {
            Thread t = new Thread(new ThreadStart(ThreadJob));
            t.IsBackground = true;
            t.Start();
        }

        private void ThreadJob()
        {
            RandNum = GetRandomNum();

            if ( OnResultHandler != null )
            {
                OnResultHandler(RandNum);
            }
        }

        int GetRandomNum()
        {
            return 5;
        }
    }
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16935203
Some explanations: MyClass defines event OnResultHandler which reports to subscriber result of thread calculation.
Form1 creates MyClass instances and subscribes to their OnResultHandler event.
OnResultHandler(RandNum) - this is actually call to class_OnResultHandler function.
class_OnResultHandler function is called in a worker thread context and cannot access directly form controls. It uses Invoke call which calls HandleResult function in the context of main application thread. By the way, using Invoke also solves the problem of thread safety.
Just for fun, it is possible to write one function which calls itself, and remove HandleResult function:

        void class_OnResultHandler(int result)
        {
            if ( this.InvokeRequired )
            {
                this.Invoke(new ResultHandler(this.class_OnResultHandler), new object[] { result });
            }
            else
            {
                int n = 0;

                try
                {
                    n = Int32.Parse(textBox1.Text);
                }
                catch (Exception)
                {
                }

                n += result;

                textBox1.Text = n.ToString();
            }
        }

See also:
http://www.codeproject.com/csharp/workerthread.asp
0
 

Author Comment

by:axnst2
ID: 16935639
Thanks Alex,  That worked great!
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

632 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question