Why SynchronizationContext is so important

suggest change

Consider this example:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = RunTooLong();
}

This method will freeze the UI until RunTooLong has completed. The application will be unresponsive.

You can try to run the inner code asynchronously:

private void button1_Click(object sender, EventArgs e)
{
    Task.Run(() => label1.Text = RunTooLong());
}

But this can fail because the inner body may run on a non-UI thread, and it shouldn’t change UI properties directly:

private void button1_Click(object sender, EventArgs e)
{
    Task.Run(() =>
    {
        var label1Text = RunTooLong();

        if (label1.InvokeRequired)
            label1.BeginInvoke((Action) delegate() { label1.Text = label1Text; });
        else
            label1.Text = label1Text;
    });
}

Do not forget to use this pattern. Or capture the UI context and post back with SynchronizationContext.Post:

private void button1_Click(object sender, EventArgs e)
{
    var context = SynchronizationContext.Current;
    Task.Run(() =>
    {
        var label1Text = RunTooLong();
        context.Post((obj) =>
        {
            label1.Text = label1Text;
        }, null);
    });
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents