Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms form freezes

Tags:

c#

.net

winforms

On a form (F1) i have a button, from which if i create another form (lets call it F2) and show it there's no problem

but i'd like to do something like this

Some thread in my app is running a connection and listens for messages from a server. when a message arrives, my main form is registered to get an event that runs a function. From that function i'm trying to create and show the F2 type form (empty, nothing modified in it): it shows it but then it freezes my application.

more exactly:

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();
    }
}
like image 661
Andrei S Avatar asked May 19 '10 08:05

Andrei S


1 Answers

I think the reason is you are performing cross thread operations. You need to put the creation of the form on the UI thread before creating form2. I think following will help you

  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();
         }
      }
  }
like image 190
Ram Avatar answered Oct 05 '22 08:10

Ram