I saw many code that they use BeginInvoke to update UI from another thread. is it possible to update UI from async function without BeginInvoke ?
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;
}
Edit
see the below code i have got from a link which show that without BeginInvoke we can update UI when using task.run.
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;
}
So tell me synchronizationContext and BeginInvoke both are same ? which one should use to update UI from different thread ? which one is most efficient ?
please guide me i am new in async/await & Task usage.