Making threadsafe calls : C# 2005
Peter Osucha <[email protected]> Tue, 19 Jun 2007 14:25:16 -0400
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Message-ID | <[email protected]> |
Hi guys,
=20
I occasionally forget (well more often than not I cheat and ignore the
errors) to make threadsafe calls to form controls. A good example I am
facing now - I have an object ('Instrument') that is handling messages
from a connected actual hardware instrument by way of a TCP Socket
connection. This Instrument object raises many events so that a
subscribing form containing an object instance can provide feedback to
the user.
=20
So I have reviewed the 'How to make thread safe calls to Windows Form
Controls' topic in MSDN and I am puzzled by the example (or I just don't
understand it well). The topic offers a code sample (shown below)...
=20
// This event handler creates a thread that calls a=20
// Windows Forms control in a thread-safe way.
private void setTextSafeBtn_Click(
object sender,=20
EventArgs e)
{
this.demoThread =3D=20
new Thread(new ThreadStart(this.ThreadProcSafe));
=20
this.demoThread.Start();
}
=20
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
this.SetText("This text was set safely.");
}
=20
It seems that to implement this type of thread-safe calling will require
a whole lot of code (it seems that I will need such a 'setup' for
modifying each and every form control I want to modify.
=20
Maybe a more concrete example of what I'm talking about would be useful.
My Instrument object raises among other events a 'DataReceived() event'
which the form has a handler for. When this event is handled by the
form, it updates several controls on the form. So I can see how I would
create a 'demoThread' in the event handler that calls a separate method
(similar to 'ThreadProcSafe' in the example above) but it seems that I'd
have to call several different 'ThreadProcSafe' methods to handle all
the controls updating I require. I guess I could have the newly created
friend call a method called UpdateFormControls (that updates every
control on the form whether its needed or not) but that seems like a
not-too-good way to do the updating.
=20
Surely I'm missing something. Any comments?
=20
Sincerely,
peter
=20
=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
This list is hosted by DevelopMentor=AE http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com