间歇地在线程中显示表单

间歇地在线程中显示表单

本文介绍了Form.Show()间歇地在线程中显示表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打开文件时,我需要显示一个进度对话框,这是一项耗时的操作.为此,我在打开文件功能中使用了以下命令:

I need to show a progress dialog while opening a file, which is a time consuming operation. To do so, I am using following inside my open file function:

           //some code
           ...
           ...
           ...
           bool done = false;

            //Show progress in a separate thread.
            System.Threading.ThreadPool.QueueUserWorkItem((x) =>
            {
                using (var progressDialog = new ProgressDialog())
                {
                    progressDialog.TopMost = true;
                    progressDialog.Show();

                    while (!done)
                    {
                        if(progressDialog.Message != this.strProgressMsg)
                            progressDialog.Message = this.strProgressMsg;

                        Application.DoEvents();
                    }

                    progressDialog.Close();
                }
            });

           ....
           ....
           done = true;
           ....
           ....

问题:进度栏对话框有时会显示,有时则不会.我的文件打开功能在主线程中运行.有人可以指出正确的侦查原因,为什么会发生这种情况?

The Problem:Progressbar dialog shows up some times and sometimes it doesn't. My file open function runs in the main thread. Can someone please point me in the right detection as why this might be happening?

推荐答案

您已经倒过来了.它的工作方式如下:

You have this backwards. Here's how it should work:

  1. 分离一个线程以打开文件,并使用progressDialog.Invoke()使其回调主线程以执行GUI更新. (它不应该设置strProgressMsg并等待其他东西来注意到更改-让它直接将更新发送到对话框.)
  2. 从主线程以模态显示进度对话框.
  1. Spin off a thread to open the file, and have it call back to the main thread using progressDialog.Invoke() to perform GUI updates. (It should not set strProgressMsg and wait for something else to notice the change -- have it send the update straight to the dialog.)
  2. Show the progress dialog modally from the main thread.

是这样的:

using (var progressDialog = new ProgressDialog()) {
    progressDialog.TopMost = true;

    System.Threading.ThreadPool.QueueUserWorkItem((x) =>
    {
        try {
            // this represents whatever loop you use to load the file
            while (...) {
                // do some work loading the file

                // update the status
                progressDialog.Invoke(new MethodInvoker(
                    () => progressDialog.Message = "Hello, World!"));
            }
        } finally {
            // done working
            progressDialog.Invoke(new MethodInvoker(progressDialog.Close));
        }
    });

    // this will block until the thread closes the dialog
    progressDialog.ShowDialog();
}

这篇关于Form.Show()间歇地在线程中显示表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:42