C# Winforms 卡住并转到“无响应";状态 [英] C# Winforms getting stuck and go to "Not responding" state

查看:24
本文介绍了C# Winforms 卡住并转到“无响应";状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Winforms C#.net 应用程序.

I am working on a Winforms C#.net application.

public partial class FormMain : Form
{
private bool cancelQueryWaitRequested = false;

public FormMain()
{
        InitializeComponent();
}

private async void btnQueueStart_Click(object sender, EventArgs e)
{
    QueryFinishedWait();
}

private int QueryFinishedWait()
{
        int i = 1;
        reQueueUIStart();
        groupWaitQueue.Visible = true;
        for (i = 0; i < 20; i++)
        {
            lblQueueWaitSeconds.Text = (20 - i).ToString();
            Thread.Sleep(1000);

            if (cancelQueryWaitRequested)
                break;
        }
        groupWaitQueue.Visible = false;
        reQueueUIStop();
        return i;
    }
 }

当我执行此操作时,应用程序变为无响应",我可以看到处理器使用率非常高.

When I execute this, the application goes "Not responding" and I can see the Processor usage goes very high.

但是当我在 btnQueueStart_Click 中运行相同的循环时,它可以正常工作.

But when I run the same loop within btnQueueStart_Click it works properly.

我知道我做错了什么,仍然不知道是什么.

I know I am doing something wrong, still can't figure what.

提前致谢.

推荐答案

但是当我在 btnQueueStart_Click 中运行相同的循环时,它可以正常工作.

But when I run the same loop within btnQueueStart_Click it works properly.

那是因为事件处理程序是异步的,但是在调用方法时会破坏它.

That's because the event handler is async, but you destroy that when calling your method.

private async void btnQueueStart_Click(object sender, EventArgs e)
{
    //QueryFinishedWait();
    await QueryFinishedWait();
}

async private Task<int> QueryFinishedWait()
{
    ... // await something
}

但您似乎错过了另一块异步拼图.请注意,不建议使用 Sleep() 等待.

But it seems you're missng another piece of the async puzzle. And please note that waiting with Sleep() is not recommended.

这篇关于C# Winforms 卡住并转到“无响应";状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆