threads & GUI design pattern

Z

zxc.err

Hi, i am new to c# and would use some advice from more experienced
programmers ;).

i develop an application, that retrives data from the network. i start
a threadworker, that is running in the background and pooling for new
data from the server. what is proper pattern for updating GUI?

right know, i have an interfece, lets say MyForm, implemented by main
form. the interface has methods like: setStatusBarText,
setNotificationText that access forms' controls thru Control.invoke().
however, it requires the background thread to keep the reference to
the form's instance.

is it good practise? or should i switch to events handling?

regards, michal.
 
G

Guest

Even with events, the event handler runs in the context of the caller, so
those events will still have to call Control.Invoke. How to "best" handle
this really depends on the application. You could just raise the event and
let the consumer worry about marshaling it, or you could use your own
internal Control object to marshal to the right thread and raise from there,
so the consumer wouldn't have to know about your secondary thread.
 
E

Erel

You will still need to use Control.Invoke (inside the event handler)
as the event code will be run by the background thread.
 
H

Hilton

Michal,

Here's a really simple way:

Share a list. i.e. define IList list = new ArrayList () and make it
accessible by the thread and the form, obviously synchronize as required.
The thread just does a "list.Add ("Hello World")" and the form has a
System.Windows.Form.Timer firing every 1 sec or 0.5 seconds. It looks like:

while (this.KeepThreadRunning)
{
if (list.Count == 0)
{
Thread.Sleep (500);
}
else
{
while (list.Count > 0)
{
ShowInUI (list [0]);
list.Remove (0);
}
}

Change as appropriate, but basically the thread just adds to a list and the
UI thread pulls it out and displays it. For better efficiency use a
circular list, but if you only have a few 'operations' here and there, this
will be fine.

Hilton
 

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