Jhon said:
Hi,
How can I dispatch something from a worker thread to the UI thread ?
Thanks in advance
greetings
Read about Form.Invoke. The following code should give you the idea:
public class Foo
{
public MyFormClass TheForm; //has a TextBox called textBox; inherits
//from System.Windows.Forms.Form
public delegate void UIMessageHandler(String msg);
public static UIMessageHandler OnUIMsgProxy;
public Foo(MyFormClass form)
{
OnUIMsgProxy = new UIMessageHandler(OnUIMsg);
TheForm = form;
}
public static void OnUIMsg(String msg) //invoked on UI thread
{
//add new msg to the top of the current text
String curText = TheForm.textBox.Text;
if (curText.Length > 28000)
curText = curText.Substring(0,25000);
TheForm.textBox.Text = msg + "\r\n" + curText;
TheForm.textBox.Refresh();
}
/*
To insert text to the UI from another thread, the other thread calls:
Foo.UIMsgInvoke("here is some text for the UI");
/*
public static void UIMsgInvoke(String str)
{
//invoke the message writer on the UI thread
Object [] msg = new Object[1];
msg[0] = str;
if (TheForm.IsHandleCreated)
TheForm.Invoke(OnUIMsgProxy, msg);
}
}