Custom events from background threads

  • Thread starter Thread starter Thomas Themel
  • Start date Start date
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,
 
if I understand your problem correctly then you just could have:

private bool CheckForCopy(IThingy toCopy)
{
// check if you are in the correct thread
if ( this.InvokeRequired )
{
return (bool) Invoke(new
ThingyRepository.ThingyCheckDelegate(CheckForCopy), new object[] {toCopy}) ;
}
else
CheckForCopy( toCopy );
}
 
Wiktor Zychla said:
if I understand your problem correctly then you just could have:

[...]

Ah yes. This looks better, at least in terms of maintainability and code
clutter.

I'm still a bit surprised that I have to deal with an issue that is so
general in scope in user code...

I would have expected some kind of 'thread bound delegate' that could be
set to run on a defined UI thread at creation time, or at least
something a bit more elegant.

thanks anyway,
 
Back
Top