By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 852 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

Handling Control UI Events in Worker Threads

P: n/a
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

Aug 22 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jordan wrote:
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

--
You can email me directly by removing the NOSPAm below
xm**********@gmxNOSPAm.netNOSPAm
Aug 22 '06 #2

P: n/a
Andreas,

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

Jordan

Aug 22 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.