Windows 显示桌面导致 WinForms 元素停止更新(2)

Windows Show Desktop causes WinForms elements to stop updating (2)

有没有一种简单的方法可以使表单上的元素在我单击 Windows 显示桌面后仍保持更新?以下代码更新 textBox1 中的值,直到我单击 Windows 显示桌面(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 交互,则上述方法不可行。