Paralel Events example

So you wanna have 2 events running at the same time (parallel)?
nope - they will run as a stack, we need , threads!
so typically I would recommend using the TPL library but sometimes its not exactly what you need, and sometimes you work with .Net 3.5.

If we just start new thread in WinForms we also get cross trread exception... - this is solved with delegates!

Here is my code for 2 textboxes with doubleClick event to write to a 3rd textbox, 1st textbox by an event, the other textbox by a thread.

note that the event are still in a stack although they get a different class.
the threads should work without a class but this is a pattern for "heavier" work:

public partial class Eventer : Form
{
     int id = 10;
     public Eventer()
    {
           InitializeComponent();
     }
    
    private void txtEnter_DoubleClick(object sender, EventArgs e)
    {
         cWriter cw = new cWriter(id++);
         cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);
         cw.StartWriting();
     }

      private void txtStartThread_DoubleClick(object sender, EventArgs e)
     {
           object oID = id++;
           Thread t = new Thread(new ParameterizedThreadStart(StartSingleThread));
           t.Start(oID);
      }

      void StartSingleThread(object oID)
      {
            int id = (int)oID;
            cWriter cw = new cWriter(id);
            cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);
            cw.StartWriting();
      }

     void cw_SendBack(string str)
     {  
            if (txtBigBox.InvokeRequired)
           {    
                 SetTextCallback d = new SetTextCallback(cw_SendBack);
                 this.Invoke(d, new object[] { str });
           }
           else
          {
                 txtBigBox.AppendText(str);
           }           
      }

     delegate void SetTextCallback(string text);
}//end class form

public class cWriter
{
       public delegate void Writer(int id);
       public event Writer StartWrite;
       public delegate void BackToTextBox(string str);
       public event BackToTextBox SendBack;
       int id;
       public cWriter(int id)
      {
            this.id = id;
      }

       public void StartWriting()
      {
            StartWrite += new Writer(cWriter_StartWrite);
            StartWrite(id);
       }

       void cWriter_StartWrite(int id)
       {
             for (int i = 0; i < 10; i++)
             {
                     SendBack(id.ToString() + " " +
                     DateTime.Now.ToLongTimeString() + "\r\n");
                     System.Threading.Thread.Sleep(300);
                     Application.DoEvents();
              }
       }
}//end cwriter

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

Asp.Net Ending Response options, Response.End() vs CompleteRequest()

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem