BeginInvoke and SynchronizationContext both does the same thing

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
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.

Continue reading...
 
Back
Top