WinForms表单冻结

时间:2010-05-19 08:10:53

标签: c# .net winforms

在表格(F1)上我有一个按钮,如果我创建另一个表单(让我们称之为F2)并显示它没有问题

但我想做这样的事情

我的应用中的某些线程正在运行连接并侦听来自服务器的消息。当消息到达时,我的主表单被注册以获得运行函数的事件。从该函数我试图创建并显示F2类型表单(空,没有修改):它显示它然后它冻结我的应用程序。

更确切地说:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
    }

    private void Form1_OnMessageReceived(object sender, MessageEventArgs e) {
        Form2 f2 = new Form2();
        f2.Show();
    }
}

2 个答案:

答案 0 :(得分:7)

我认为原因是您正在执行跨线程操作。在创建form2之前,您需要在UI线程上创建表单。我想以下会帮助你

  public delegate void ShowForm(object sender, MessageEventArgs e);
  public partial class Form1 : Form
  {
     public Form1()
     {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
     }

     private void Form1_OnMessageReceived(object sender, MessageEventArgs e)
     {
         if (this.InvokeRequired)
         {
            this.BeginInvoke(new ShowForm((Form1_OnMessageReceived), new object[] { sender, e }));
         }
         else
         {
            Form2 f2 = new Form2();
            f2.Show();
         }
      }
  }

答案 1 :(得分:2)

使用Ram的代码我终于得到了它并且它可以工作

感谢名单!

public delegate void ShowForm(object sender, MessageEventArgs e);

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
    }

     private void Form1_OnMessageReceived(object sender, MessageEventArgs e)
     {
         ShowForm2(sender, e);
     }

    private void ShowForm2(object sender, MessageEventArgs e)
    {
        if (this.InvokeRequired)
        {
            ShowForm f = new ShowForm(ShowForm2);
            this.Invoke(f, new object[] { sender, e });
        }
        else
        {
            Form2 f2 = new Form2();
            f2.Show();
        }
    }
}