T
Thomas Themel
Hi,
I'm currently trying to get a C# application's main form to react to
events from background threads. My current understanding is that I have
to use the following construct if I want to have any GUI interaction in
the event handlers
public class ThingyRepository
{
[...]
public delegate bool ThingyCheckDelegate(IThingy toCheck) ;
// fires from random background threads
public static event ThingyCheckDelegate ThingyCopyRequested ;
[...]
}
public class MainForm : System.Windows.Forms.Form
{
[...]
MainForm()
{
[...]
ThingyRepository.ThingyCopyRequested +=
new ThingyRepository.ThingyCheckDelegate(CheckForCopyFromThread) ;
[...]
}
[...]
private bool CheckForCopyFromThread(IThingy toCopy)
{
// this can be called from any thread, so we can't touch the
// user interface directly
return (bool) Invoke(new ThingyRepository.ThingyCheckDelegate(CheckForCopy), new object[] {toCopy}) ;
}
private bool CheckForCopy(IThingy toCopy)
{
// do something that involves the UI
}
[...]
}
If this is indeed the only way to do this, I'd basically have to
implement every event handler twice and construct that annoying Invoke
call just to ensure that the real handler gets executed on the correct
thread.
Since this really seems too cumbersome to be true, and the problem is
seemingly obvious, I assume there is something I'm missing here.
Could someone enlighten me?
thanks,
I'm currently trying to get a C# application's main form to react to
events from background threads. My current understanding is that I have
to use the following construct if I want to have any GUI interaction in
the event handlers
public class ThingyRepository
{
[...]
public delegate bool ThingyCheckDelegate(IThingy toCheck) ;
// fires from random background threads
public static event ThingyCheckDelegate ThingyCopyRequested ;
[...]
}
public class MainForm : System.Windows.Forms.Form
{
[...]
MainForm()
{
[...]
ThingyRepository.ThingyCopyRequested +=
new ThingyRepository.ThingyCheckDelegate(CheckForCopyFromThread) ;
[...]
}
[...]
private bool CheckForCopyFromThread(IThingy toCopy)
{
// this can be called from any thread, so we can't touch the
// user interface directly
return (bool) Invoke(new ThingyRepository.ThingyCheckDelegate(CheckForCopy), new object[] {toCopy}) ;
}
private bool CheckForCopy(IThingy toCopy)
{
// do something that involves the UI
}
[...]
}
If this is indeed the only way to do this, I'd basically have to
implement every event handler twice and construct that annoying Invoke
call just to ensure that the real handler gets executed on the correct
thread.
Since this really seems too cumbersome to be true, and the problem is
seemingly obvious, I assume there is something I'm missing here.
Could someone enlighten me?
thanks,