本文介绍了为什么form.showdialog()工作和form.show()不在以下代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中我有一个监视器,看看文件是否已更改,如果它已更改我显示在窗体上更改的信息,但如果我使用form.Show()为此冻结,但form.showDialog )工作正常,这两者之间的区别和如何确定使用哪一个

In the following piece of code I have a watcher that look if file has changed and if it has changed I show the changed information on a form but if i use form.Show() for this it freezes but form.showDialog() works fine, what is the difference between these two and how to determine which one to use

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        _watcher.EnableRaisingEvents = false;
        try
        {
            if (_displayPatientInfo != null)
            {
                _displayPatientInfo.Dispose();
            }
            GetPatientInfo(e.FullPath);
            using (StreamReader sr = new StreamReader(e.FullPath, Encoding.Default))
            {
                String line;
                line = sr.ReadToEnd();

                if (line.IndexOf("<IsPatientFixed>") > 0)
                {
                    var value = GetTagValue(line, "<IsPatientFixed>", "</IsPatientFixed>");
                    if (value == "true" || value == "True")
                    {

                        _displayPatientInfo = new frmPatientInfoDisplay();
                        _displayPatientInfo.SetData(_patientInfo);
                        _displayPatientInfo.ShowDialog();

                    }
                }
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            _watcher.EnableRaisingEvents = true;
        }
    }


推荐答案

@Habib说当你调用ShowDialog()的代码之后,这个不执行,直到你关闭窗体,你的观察者会被卡住。

As @Habib said when you call ShowDialog() the code after this is not executed until you close the form and your watcher will be stuck.

你的问题是,运行在不同的线程然后你的主要形式,这就是为什么当你调用Show()它会冻结你的应用程序,因为它试图访问的一部分内存是由你的主线程拥有的。
要解决这个问题,你可以使用Invoke(Delegate)来显示或者配置_displayPatientInfo表单。

Your problem is that the watcher is running on a different thread then your main form, that's why when you call Show() it will freeze your application because it's trying to access a portion of memory that is owned by your main thread.To fix this you can use Invoke(Delegate) when you want to show or dispose _displayPatientInfo form.

    Executes the specified delegate on the thread that owns the control's underlying window handle.

这篇关于为什么form.showdialog()工作和form.show()不在以下代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:43