Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在不冻结Framework2.0 UI的情况下睡眠_C#_.net - Fatal编程技术网

C# 在不冻结Framework2.0 UI的情况下睡眠

C# 在不冻结Framework2.0 UI的情况下睡眠,c#,.net,C#,.net,在我的程序中,我有两个线程,第一个线程在(isRunning){ 对于第二个线程方法,我需要它休眠一分钟,而这是真的。 我当前代码面临的问题是,在任务管理器中,我的程序得到了一个没有响应的 请注意,我使用的是Framework2.0,如何解决这个问题 private void initialize() { MyWeb.connectToServer(); commandThread = new Thread(checkForCommandThread); // T

在我的程序中,我有两个线程,第一个线程在(isRunning){

对于第二个线程方法,我需要它休眠一分钟,而这是真的。 我当前代码面临的问题是,在任务管理器中,我的程序得到了一个
没有响应的

请注意,我使用的是Framework2.0,如何解决这个问题

private void initialize() {
        MyWeb.connectToServer();
        commandThread = new Thread(checkForCommandThread); // The thread that I need not to freeze the program
        commandThread.Start();
    }

private void checkForCommandThread() {
        while (isRunning) {
            Thread.Sleep(10000);
            // while this thread is sleeping, the program should not be frozen
            // do the work here, after the sleep
        }
    }

好的,假设你有这样的代码

    public static bool _isRunning = false;

    private void button1_Click(object sender, EventArgs e)
    {
        _isRunning = true;
        var thread = new Thread(DoWork) {IsBackground = true};
        thread.Start();

        while (_isRunning)
        {
            //HERE GOES THE MAGIC
            Application.DoEvents();
        }
    }

    private static void DoWork()
    {
        System.Threading.Thread.Sleep(20000);
        _isRunning = false;
    }

我的程序似乎没有响应,因为我的另一个线程一直在运行,没有任何睡眠,并且运行得尽可能快,因此程序没有响应,占用了高达13%的CPU


一个简单的
线程。Sleep(10);
修复了所有问题您可能正在寻找类似的东西:您不需要阻止UI线程。这是针对更高的框架,但深入讨论了您的问题。我看到3个反对票,并且没有人向我提供框架2.0的有效答案显然是您的“第二个线程”是UI线程,或者UI线程本身出于某种原因正在等待第二个线程。通常,您不应该调用
thread.Sleep()
。即使在.NET 2.0中,也存在异步机制,允许您延迟代码的执行而不占用整个线程。如果您想要一个好的答案,请提供清楚说明问题背景的答案。请参阅,以获取有关提出清晰、可回答问题的建议。下面是关于如何以及何时提交的详细说明HT使用这个“doStices”的东西:但是只有傻瓜才会认为你总是不能“阻止UI线程”。