Windows应用程序“(未响应)”但最终完成了 [英] Windows app "(not responding)" but eventually completes

查看:297
本文介绍了Windows应用程序“(未响应)”但最终完成了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个非常简单的应用程序来读取文本文件,然后相应地处理它。

在大文件读取期间,没有反馈用户该应用程序实际上仍在运行。





我填充ListBox,所以我在读取过程中每2000行强制一个ListBox.Refresh()。只要我的应用程序具有焦点,这种方法就可以正常工作,但对于大型文件,我的用户将在计算机上执行其他操作,以便远离应用程序。





如何强制Windows继续在后台更新应用程序?

这是基本的读代码......没什么特别的:



I wrote a very simple app to Read a text file, then process it accordingly.
During the Read on a large file, there is no feedback to the user that the app is actually still running.


I fill a ListBox, so I force a ListBox.Refresh() every 2000 lines during the read. This works fine as long as my app has focus, but for large files, my users will do other things on the computer that take focus away from the app.


How can I force Windows to keep updating the app in the background?
Here's the basic read code...nothing special:

this.Cursor = Cursors.WaitCursor;
    lbOriginalFile.Items.Clear();
    string strStreamLine = "";
    int nPosition = 0;
    int nLineCount = 0;
    if (System.IO.File.Exists(GCodeFilePath) == true)
    {

        using (System.IO.StreamReader sr = new System.IO.StreamReader(GCodeFilePath))
        {
            strStreamLine = sr.ReadLine();
            while (strStreamLine != null)
            {
                nLineCount++;
                lbOriginalFile.Items.Add(strStreamLine);
                lblCount.Text = nLineCount.ToString();
                lbOriginalFile.Refresh();
                lblCount.Refresh();
                strStreamLine = sr.ReadLine();
            }
            nListBoxArray[nPosition] = nPosition;
        }
    }
    this.Cursor = Cursors.Default;





我的尝试:



上面的代码显示尝试更新计数器和刷新控件。



What I have tried:

Above code shows trying to update a Counter and Refreshing controls.

推荐答案

迫使Windows继续更新无法解决问题你的应用程序。



问题是你正在保持应用程序的UI线程(启动线程)如此忙于对文件进行处理而无法处理绘制在应用程序消息队列中堆叠的消息。



将文件处理移动到后台线程,然后释放UI线程以绘制窗口和其他控件。



您可以使用BackgroundWorker来完成工作,它甚至可以为您提供一个方便的方法,以便在需要时通知UI线程进度。



您甚至不需要调用.Refresh来控制绘画。



Google:C#backgroundworker [ ^ ]
The problem isn't going to be resolved with "forcing Windows to keep updating" your app.

The problem is that YOU are keeping the UI thread of your app (the startup thread) so busy doing work on the file that it cannot process the paint messages stacking up in your apps message queue.

Move the the file processing to a background thread and you free up the UI thread to paint your window and other controls.

You can use a BackgroundWorker to do the work and it even gives you a handy method for notifying the UI thread of progress if you want.

You won't even need the calls to .Refresh to get the controls to paint.

Google: "C# backgroundworker"[^]


这篇关于Windows应用程序“(未响应)”但最终完成了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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