Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
Please help me to write a code inner a button1 in form1 and show form2 so that i still work with button in the same time with button1 in form1 and another control in form2 but this makes the window disappear immediately?

this is my code :

C#
private void button1_Click(object sender, EventArgs e)
     {
         ThreadStart thrStart = new ThreadStart(Show);
         Thread thr = new Thread(thrStart);
         thr.Start();

         for (int i = 0; i < 1000; i++)
         {
             for (int j = 0; j < 1000; j++)
             {
                 for (int k = 0; k < 1000; k++)
                 {
                 }
             }
         }
         label1.Text = "12";
     }
     public void Show()
     {
         Form2 frm2 = new Form2();
         frm2.show();
     }
Posted
Updated 12-Apr-12 3:53am
v2
Comments
Sergey Alexandrovich Kryukov 12-Apr-12 20:52pm    
Nothing is clear. What is "inner a button"? The code looks like gibberish. What those nested loop are supposed to do? Why thrStart is executed in the separate thread and why nested loops are executed in UI thread? It could be just the opposite...
--SA

1 solution

The question and the code do not seem to make any sense.

Three nested loop do nothing, but the should not be executed in the UI thread, as the execution may take some time. You should never execute in a UI thread anything which contains blocking calls of just take extended period of time.

From the other hand, Show should not be called in a separate thread. First of all, it cannot work, because you cannot call any methods or properties of currently running UI from any thread except the UI thread where the currently running System.Windows.Forms.Application instance is executed. You can only work with UI indirectly, via the invocation.

This is explained in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

More importantly, you never need to run the method Show from a separate thread. This method should be called directly from the UI thread. The method creates and shows the form and returns immediately.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900