Handling Control UI Events in Worker Threads

J

Jordan

I need to handle UI events in a worker thread instead of the primary UI
thread. In C#, is the normal UI event handling behavior to run in a
context thread on the thread pool or are events always invoked on the
primary UI thread?

Thanks,
Jordan
 
A

Andreas Mueller

Jordan said:
I need to handle UI events in a worker thread instead of the primary UI
thread. In C#, is the normal UI event handling behavior to run in a
context thread on the thread pool or are events always invoked on the
primary UI thread?

Thanks,
Jordan

Normally the events are invoked and handled inside the GUI thread, but
nothing keeps you from handling them in another thread. You just have to
be aware that WinForms are not thread safe out of the box.

Here is an example of a form that handles the KeyDown event of a TextBox
in a ThreadPool thread and syncronizes back to the UI:

namespace TestApp
{
class Program
{
[STAThread]
static void Main()
{
Application.Run(new UIEventInThreadTestForm());
}
}
class UIEventInThreadTestForm : Form
{
public UIEventInThreadTestForm()
{
Size = new Size(500, 500);

textBox.Location = new Point(10, 10);
textBox.Size = new Size(100, 10);
Controls.Add(textBox);

textBox.KeyUp += new KeyEventHandler(textBox_KeyUp);

label.Location = new Point(120, 10);
label.Size = new Size(100, 20);
Controls.Add(label);
}

void textBox_KeyUp(object sender, KeyEventArgs e)
{
ThreadPool.QueueUserWorkItem(
new WaitCallback(HandleKeyDownAsync), e);
}
private void HandleKeyDownAsync(object keyEventArgs)
{
KeyEventArgs e = (KeyEventArgs)keyEventArgs;

UpdateLabel((char)e.KeyCode);
}

private void UpdateLabel(char key)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<char>(UpdateLabel), key);
return;
}

label.Text = label.Text + key;
}

private TextBox textBox = new TextBox();
private Label label = new Label();
}
}

HTH,
Andy
 
J

Jordan

Andreas,

Thank you for your speedy reply. This answers what I needed to know.
Thank you very much!

Jordan
 

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