I have a task that might take a while to complete.
I have tried a simple demo but it locks up the GUI thread for some reason. I thought the task would be asynchronous and the GUI would update whilst the task is running.
Is this possible with a Task?
private void button5_Click(object sender, EventArgs e)
{
var task = Task.Factory.StartNew(() => DoSomething());
while (!task.IsCompleted)
{
label1.Text += ".";
if (label1.Text.Length == 5)
label1.Text = ".";
}
}
private void DoSomething()
{
Thread.Sleep(5000);
}
UPDATE: After Damien’s answer I tried the below but the CPU ramped up
private void button5_Click(object sender, EventArgs e)
{
var task = Task.Factory.StartNew(() => DoSomething());
}
public delegate void dgUpdateLabel();
private void UpdateLabel()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new dgUpdateLabel(UpdateLabel), new object[] { });
}
else
{
label1.Text += ".";
if (label1.Text.Length == 5)
label1.Text = ".";
}
}
private void DoSomething()
{
var task = Task.Factory.StartNew(() => Sleep());
while (!task.IsCompleted)
{
UpdateLabel();
}
}
private void Sleep()
{
Thread.Sleep(5000);
}
UPDATE2: I think the speed of trying to update the label is too fast for it to handle. If you put a Thread.Sleep(500) after the UpdateLabel method call it works as expected.
Updating according to our chat 🙂 :