Threaded Cross-Class Winform Manipulation

  • Thread starter Thread starter i
  • Start date Start date
I

i

Hi,

I'm trying to get a seperate class, initialized by a form class, to
manipulate certain objects on the form (ex: add to a listbox). The
manipulation will occur via a thread that is not the normal WinForm GUI
thread. How would I go about doing this?

I have this code for cross-thread WinForm manipulation, but only from within
the WinForm class:

public delegate void LogDelegate(string txt);

public void Log(string txt)
{
if (InvokeRequired)
{
Invoke(new LogDelegate(Log), txt);
return;
}

lstLog.Items.Insert(0, DateTime.Now.ToString("T") + " - " + txt);
}

Thanks,
Ian
 
i said:
I'm trying to get a seperate class, initialized by a form class, to
manipulate certain objects on the form (ex: add to a listbox). The
manipulation will occur via a thread that is not the normal WinForm GUI
thread. How would I go about doing this?

I have this code for cross-thread WinForm manipulation, but only from within
the WinForm class:

public delegate void LogDelegate(string txt);

public void Log(string txt)
{
if (InvokeRequired)
{
Invoke(new LogDelegate(Log), txt);
return;
}

lstLog.Items.Insert(0, DateTime.Now.ToString("T") + " - " + txt);
}

You'd do it in exactly the same way as the above, but using form.Invoke
and form.ListLog or however you want to expose the ListBox to other
classes. Of course, you could make sure that the only thing which has
access to the controls is the form class itself, and just give
thread-safe ways of performing certain operations (as you have above).
Personally, I think that's generally preferable to letting other
objects manipulate the UI, but it depends on the situation.
 

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

Back
Top