'CallBack'에 해당되는 글 1건

  1. 2007/08/27 Calling Your Main Thread From A Worker Thread In C#
2007/08/27 08:37

Calling Your Main Thread From A Worker Thread In C#

There are many cases where it is necessary to let your main application know that a thread has completed. Your main application could spawn some threads to do background work and then when the threads have completed their work they could return the results back to the main application. This would be beneficial since it would leave the main thread free and ready to respond to the user. We will create a new application that will spawn two thread that will each modify a label on a form, when the classes are finished executing they will call back to the main thread to let it know that they have completed execution.

using System;
using SystemThreading;
using System.Windows.Forms;

namespace WindowsApplication1
{       
   public class Counter
   {       
      private Label LabeltoUpdate;
      private int MaxCount;
      privateCallBackCallBackMethod;
       
      public Counter(Label l,int max, CallBack cb)
      {
          LabeltoUpdate = l;
          MaxCount = max;
          CallBackMethod = cb;
      }

      public void BeginProcessing()
      {
          int i;

          for(i=1;i < MaxCount; i  )
          {
             LabeltoUpdate.Text = i.ToString();
             LabeltoUpdate.Refresh();
          }

          //Tell the main thread we have completed
          CallBackMethod(i,Thread.CurrentThread.Name);
      }
   }
}

using System.Threading;

private void button1_Click(object sender, System.EventArgs e)
{
   Counter c1 = new Counter(label1,3000,new CallBack(ThreadCompleted));
   Counter c2 = new Counter(label2,1500,new CallBack(ThreadCompleted));

   Thread t1 = new Thread(newThreadStart(c1.BeginProcessing));
   Thread t2 = new Thread(new ThreadStart(c2.BeginProcessing));

   t1.Name = "Counter Thread 1";
   t2.Name = "Counter Thread 2";

   t1.Start();
   t2.Start();
}

private void ThreadCompleted(int intTotal,string strName)
{
   MessageBox.Show("Thread "   strName  
                      " has completed at "   intTotal.ToString());
}

Trackback 0 Comment 0