Windows Show Desktop导致WinForms元素停止更新(2)



有没有一种简单的方法可以让表单上的元素即使在我单击Windows显示桌面后也保持更新?以下代码更新textBox1中的值,直到我单击Windows Show Desktop(Windows 10-单击屏幕右下角(。我不喜欢使用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;
}   

解决此问题的一种方法是使用Task.Run方法将CPU绑定的工作卸载到ThreadPool线程:

private async void Button1Click(object sender, EventArgs e)
{
int n = 0;
while (true)
{
n = await Task.Run(() => Increment(n));
textBox1.Text = n.ToString();
}
}

此解决方案假定Increment方法不会以任何方式在内部与UI组件交互。如果您确实需要与UI交互,那么上述方法不是一个选项。

最新更新