Callback methods are executed in different threads. How have the main thread do the job???

B

Bob Rock

Hello,

exploring more and more the .NET framework I've seen that threads are
often employed by the framework, for example in:

- callback methods on timers
- async operations (async receives on message queues, etc.)

Wanting to avoid executing the event handler code in a different
thread is there a *standard* way (something like a pattern) to
accomplishing this??? I remember having read something relative to the
need to update UIs only from the thread that creates them. Having a
worker thread that needs to update a UI element how can the update be
done by the thread that created the UI on behalf of the worker
thread??? I'm asking because I believe that the same approach could be
a possible answer to my initial question.


Thx.
Bob Rock
 
G

Guest

Bob,
Having a
worker thread that needs to update a UI element how can the update be
done by the thread that created the UI on behalf of the worker
thread???

Typically you would do this by having an event handler on your form to do
the work of updating the GUI. As for calling the event handler from another
thread, any class that descends from Control { for example Form } has methods
for this purpose:

BeginInvoke
EndInvoke
Invoke

These methods assure that the thread that created the control will execute
the event delegate that you specify; you can safely call these 3 methods from
your worker thread. See documentation for explanations and examples...

As far as patterns are concerned - I forget the name exactly but there is an
"Event and Delegate Pattern" out in MSDN. The pattern explains the required
pieces for making a custom event handler and it provides naming convention
recommendations for the pieces...

--Richard
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Bob,

If you have a method declared in a class that inherits from Control and that
method sometimes might be executed in a worker thread (generally speeking in
a thread that has not created the control), but you want to have it executed
in the thread that has created the control, the pattern I 'd suggest (and
the pattern many developers follow) is

//Foo is declared in a class inheriting from control
ReturnType Foo(param1, param2,...)
{
if(this.InvokeRequired)
{
return (ReturnType)this.Invoke(new DelegateForFoo(Foo), new
object[]{param1, param2,....});
}

//Do some work in the UI thread

return value;
}
 

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