Events && Multi-Threading

Dear Future Me:

When you need to write a vanilla event, use the following boilerplate:

public event EventHandler<EventArgs> MyEventName

And when you need to write a vanilla cross-thread function to update the UI in a WPF application, use the following boilerplate:

Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
    SomeUIControl.Text = someValueFromThisThread;
}));

And this is in System.Windows.Threading, which is not in the Client Profile

And when you need to write a vanilla cross-thread function to update the UI in a WinForms application, use the following boiler plate:

this.BeginInvoke(new Action(() =>
{
    StringBuilder message = new StringBuilder();
    message.AppendFormat("{0:hh\\:mm\\:ss}", e.ElaspedTime);

    SomeUIControl.Text += Environment.NewLine;
    SomeUIControl.Text = message.ToString();
}));

Love,

Present Me

PS: you really should exercise more…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: