Accessing GUI from threads

  • Thread starter Thread starter Ray Mitchell
  • Start date Start date
R

Ray Mitchell

In my main dialog, which opens when my application starts
and never closes until the application completes, I have a
list box. My assembly also contains several threads. I
would like to write to the list box from my main
application as well as all the other threads. In my main
application I have a public method that adds a new item to
the listbox each time it's called. My constructor makes
the dialog object public. My intent is to call my
function from anywhere using the syntax:

MyClass.mainDialog.AddStringToList(someString);

It seems to work for the one thread I've tested it with
but I'm guessing on a lot of this. I've heard that
threads can't, or at least shouldn't access GUI, although
I'm not sure why. Does anyone forsee any problems or have
any references recommendations to explain why there are
problems with threads and GUI, and how to deal with them?
Thanks for your help!

Here is the stripped-down code:

public class MyClass : System.Windows.Forms.Form
{
public static MyClass mainDialog;

public MyClass()
{
mainDialog = this;
}

public void AddStringToList(string s)
{
this.myListBox.Items.Add(s);
}
}
 
You need to use Control.Invoke to update UI objects from another thread.
They need to be updated on the thread that created the control. The Control
Class documentation states:

Thread Safety
Only the following members are safe for multithreaded operations:
BeginInvoke, EndInvoke, Invoke, InvokeRequired, and CreateGraphics.
 
Here's a "Multithreaded Windows Forms Control Sample" that may help:

http://msdn.microsoft.com/library/d...evelopingmultithreadedwindowsformscontrol.asp
threads can't, or at least shouldn't access GUI, although

I think what you are referring to is something I've seen somewhere in the
Asynchronous documentation:

http://msdn.microsoft.com/library/d...html/cpovrasynchronousprogrammingoverview.asp

It referers to one way of making asynchronous calls: Begin Invoke and End
Invoke as not recommended for UI's because like a synchronous call it blocks
until the operation completes. It says Callbacks, polling
IAsyncResult.IsCompleted, or BeginInvoke WaitHandle EndInvoke are preferred.

--
 
Back
Top