0

I am new in TPL, Async/Await. so many things are not getting clear. so posting a exmple code here. please guide me without negative marking for my post.

My first example of BeginInvoke code given here.

private async void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            var count = 0;

            await Task.Run(() =>
            {
                for (var i = 0; i <= 500; i++)
                {
                    count = i;
                    BeginInvoke((Action)(() =>
                    {
                        label1.Text = i.ToString();

                    }));
                   Thread.Sleep(100);
                }
            });

            label1.Text = @"Counter " + count;
            button1.Enabled = true;
        }

Second example where i used SynchronizationContext to update UI.

private readonly SynchronizationContext synchronizationContext;
private DateTime previousTime = DateTime.Now;

public Form1()
{
    InitializeComponent();
    synchronizationContext = SynchronizationContext.Current;
}

private async void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    var count = 0;

    await Task.Run(() =>
    {
        for (var i = 0; i <= 5000000; i++)
        {
            UpdateUI(i);
            count = i;
        }
    });

    label1.Text = @"Counter " + count;
    button1.Enabled = true;
}

public void UpdateUI(int value)
{
    var timeNow = DateTime.Now;

    if ((DateTime.Now - previousTime).Milliseconds <= 50) return;

    synchronizationContext.Post(new SendOrPostCallback(o =>
    {
        label1.Text = @"Counter " + (int)o;
    }), value);             

    previousTime = timeNow;
} 

Please tell me BeginInvoke and SynchronizationContext both does the same thing. which one is more efficient. is there any specific scenario where BeginInvoke is good and in what kind of scenario SynchronizationContext would be good.

Mist
  • 684
  • 9
  • 30
  • On the duplicate, aside from the accepted answer also look at the .NET 4.x answer a little lower. – H H Dec 23 '18 at 09:20
  • Yes, they do the same thing in a Winforms app. The *specific* SynchronizationContext object you get is an instance of WindowsFormsSynchronizationContext and it uses BeginInvoke() to marshal the call. Using SynchronizationContext is important to libraries, they in general can't assume they are only used in a Winforms app and ought to work just as well in a WPF, UWP, ASP.NET or console app. Which have different synchronization providers. Necessarily so, Control.BeginInvoke() can't do the job anymore. – Hans Passant Dec 23 '18 at 12:24

0 Answers0