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 UI application until the RunTooLong will be completed. The application will be unresponsive.

You can try run inner code asynchronously:

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

But this code won’t execute because inner body may be run on 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)
            lable1.BeginInvoke((Action) delegate() { label1.Text = label1Text; });
        else
            label1.Text = label1Text;
    });
}

Now don’t forget always to use this pattern. Or, try SynchronizationContext.Post that will make it for you:

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

Feedback about page:

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


Synchronization Context in Async/Await:
* Why SynchronizationContext is so important

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
112 Synchronization Context in Async/Await
127 Caching
135 Pointers
147 C# Script