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
Herman van der MeerPosted Jul 19, 2007, 4:03 AM
I will have a look at the article and do some testing and debugging with my testprogram
Thanks a lot
Herman
AlanPosted Jul 18, 2007, 12:31 PM
To understand the difference between these two methods you need to know a bit about how Windows is processing messages behind the scenes. Here's a very good article on the subject:
http://www.codeproject.com/csharp/begininvoke.asp
Herman van der MeerPosted Jul 18, 2007, 6:13 AM
Only, the answer leads to a new question :-)
Thread B waits until the event is completely handled by thread A. I was hoping that thread B only sends the event and continues working. But testing the programs shows that thread B only continues when thread A has handled the event (in this case, the user must click the MessageBox button).
Can anyone explain this behaviour??? (I'm not really familiar to C#, but I cannot find this in books or Internet).
Many thanks in advance
Herman
AlanPosted Jul 17, 2007, 9:39 AM
To ensure that MyEvent is invoked from Thread A (i.e. the main UI thread) then replace:
MyEvent();
with:
this.Invoke(MyEvent);