Hello.
Event handlers for events from an object of another thread than the UI
thread cannot access UI components, as you know. If the object has
many events this precedure is painstaking. Plus the source code gets
longer and dirtier.
Note :The code below is NOT the actual code, but an example. (I say
this, because sometimes people points out that the sample code won't
complie, even if it's just an example to explain the matter. ... means
there are more codes but are omitted because those are unnecessary.)
public delegate void MessageDelegate(Worker sender, Data d);
class ObjectFromAnotherThread
{
public event MessageDelegate MessageReceived;
....
MessageReceived(this, d);
....
}
class MainForm:Form
{
....
void OnMessage(Worker sender, Data d)
{
if (InvokeRequired)
{
OnMessageDelegate d = new OnMessageDelegate(OnMessage);
this.BeginInvoke(d, new object[] { sender, d });
}
else
{
TheLabel.Text=d.ToString();
}
}
....
}
For example, if there are three events I have to write codes like
above three times. Am I using a wrong scheme? Is there any nicer,
cleaner way? I hope that I could hear some advices from you. Thank you.