Loading your form freezes because the window form user interface runs on a single thread. And the logic that you put on the Load event of this form works on this thread.
You can easily start the loop in a separate thread using BackgroundWorker in your window form. In your worker’s DoWork event, you place code that has a loop that should run without blocking your user interface. In the Form.Load event, you can start the background working component by calling the RunWorkerAsync method. In the event handler of your button, you put the code to stop the background worker by calling the CancelAsync method .
The article How to implement a form that uses the background shows how to execute it.
About your comment that you cannot update the text of the text field from the desktop component. This is because it is not allowed to change the state of a window control from another thread (your background working code runs in a separate thread). The MSDN documentation states:
Access to Windows Forms controls is not essentially thread safe. If you have two or more threads that control the state of the control, you can force the control to go into an inconsistent state. Other flow-related errors are possible, such as race conditions and deadlocks. It is important to make sure that your controls are accessed in a thread-safe manner.
An example of how you can update the state of Windows form elements from a background thread will look similar to the following (assuming that the new value is already stored in a String variable called text):
// InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; }
I borrowed this code, cut off from How to make secure calls in Windows Forms Controls . It can provide you with more information on how to handle multi-threaded window forms.
source share