Custom events from background threads

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,
 
W

Wiktor Zychla

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 );
}
 
T

Thomas Themel

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top