【问题标题】:Refresh Application Window in Loop循环刷新应用程序窗口
【发布时间】:2011-12-08 11:49:08
【问题描述】:

我有一个 Windows 窗体应用程序,其中有一个按钮。如果单击它,则会启动一个包含大量工作的大循环,这可能需要一些时间(最多几分钟)。在那个时候,窗口对任何东西都没有反应,你甚至不能移动它。怎么去这里?有我可以调用的窗口更新功能吗?我必须在新线程中运行循环吗?

【问题讨论】:

  • 很多人会告诉你不要这样做并使用单独的线程,但只是为了测试尝试将 Application.DoEvents() 放入循环中,你可能会看到表单重新绘制,你会也可以移动它。 msdn.microsoft.com/en-us/library/…

标签: c# window


【解决方案1】:

使用多线程 - 这是我不久前写的一个例子。您基本上在另一个线程上完成所有处理,因此它不会占用 GUI 线程。

http://wraithnath.blogspot.com/2010/09/simple-multi-threading-example.html

单击按钮启动一个新线程(如果您将处理线程声明为成员,则可以将其停止等,如果您想取消该进程,您还可以在处理循环中检查一个 IsProcessing 成员变量)

            //Create a new Thread start object passing the method to be started
            ThreadStart oThreadStart = new ThreadStart(this.DoWork);

            //Create a new threat passing the start details
            Thread oThread = new Thread(oThreadStart);

            //Optionally give the Thread a name
            oThread.Name = "Processing Thread";

            //Start the thread
            oThread.Start();

有处理方法

        /// <summary>
        /// Simulate doing work
        /// </summary>
        private void DoWork()
        {
            try
            {
                for (int i = 0; i < m_RecordCount; i++)
                {
                    //Sleep for 100 miliseconds to simulate work
                    Thread.Sleep(100);

                    //increment the progress bar by invoking it on the main window thread
                    progressBar.Invoke(
                        (MethodInvoker)
                        delegate
                        {
                            //Increment the progress bar
                            progressBar.Increment(1);
                        }
                    );
                }

                //Join the thread
                Thread.CurrentThread.Join(0);
            }
            catch (Exception)
            {
                throw;
            }
        }

【讨论】:

    【解决方案2】:

    我必须在新线程中运行循环吗?

    是的,您可以使用BackgroundWorker 类进行长时间操作,并通过form.Invoke 从另一个线程更新应用程序的接口。

    C# Winform ProgressBar and BackgroundWorker

    Best Practice for BackGroundWorker in WinForms using an MVP architecture

    【讨论】:

    • 我相信这是做事的“正确”方式,除非你的目标是 .net 4,它带来了一些新玩具......
    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多