Is there a simple way to have elements on a form keep updating even after I click on Windows Show Desktop? The following code updates the value in textBox1 until I click on Windows Show Desktop (Windows 10 - click on the bottom right of the screen). I prefer not to use Application.DoEvents()
private async void Button1Click(object sender, EventArgs e)
{
int n = 0;
while (true) {
Task<int> task = Increment(n);
var result = await task;
n = task.Result;
textBox1.Text = n.ToString();
textBox1.Refresh();
Update();
// await Task.Delay(200);
}
}
public async Task<int> Increment(int num)
{
return num;
}
CodePudding user response:
One way to solve this problem is to offload the CPU-bound work to a ThreadPool
thread, by using the Task.Run
method:
private async void Button1Click(object sender, EventArgs e)
{
int n = 0;
while (true)
{
n = await Task.Run(() => Increment(n));
textBox1.Text = n.ToString();
}
}
This solution assumes that the Increment
method does not interact with UI components internally in any way. If you do need to interact with the UI, then the above approach is not an option.