Threading and events

Jul 17 2007 2:42 AM

Hello

I've created a little test program with 2 threads A and B. I'd like to send an event from thread B to thread A. When I do this, the event is both send and received by thread B. This is my code (the threadfunction does nothing exept generate an event at some time):


public delegate void MyEventHandler();

namespace Test
{
    public partial class Form1 : Form
    {

        private Thread MyNewThread;
        public event MyEventHandler MyEvent;

        public Form1()
        {
            InitializeComponent();
            Thread.CurrentThread.Name = "A";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MyEvent += new MyEventHandler(TheEventHandler);
            ThreadStart func = new ThreadStart(ThreadFunction);
            MyNewThread = new Thread(func);
            MyNewThread.Name = "B";
            MyNewThread.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MyNewThread.Abort();
        }

        private void ThreadFunction()
        {
            while (true)
            {
                for (int i = 0; i < 1000000000; i++)
                {
                }
                MessageBox.Show("Event send from: " + Thread.CurrentThread.Name);
                MyEvent();
            }
        }

        private void TheEventHandler()
        {
            MessageBox.Show("Event received: " + Thread.CurrentThread.Name);
        }
    }
}

What do I do wrong?

Many thanks

Herman


Answers (4)