Looping Forever in a Windows Forms Application

后端 未结 4 528
误落风尘
误落风尘 2020-12-30 15:59

I am using Visual C# sand I\'m using a Windows Form rather than a console application. Therefore I\'m not working in Main (), but rather in the Form File. I\'m also very new

相关标签:
4条回答
  • 2020-12-30 16:37

    If you need your form to respond to a button click, the loop will have to take place in a thread other than the main thread, a BackgroundWorker would suit you.

    0 讨论(0)
  • 2020-12-30 16:50

    It seems that you are trying to create a chat client (see this example for some sample code). For long running parallel executions I recommend that you create and start a thread whose body is the while loop you mentioned.

    The key thing you have to understand is that there will be two threads of execution. One is the UI Thread who is responsible for drawing the form and reacting to events such as button clicks (note: this will loop forever reacting to events as the user interacts with the UI). The other thread is the looping background thread which you will create to listen for network information. The sample chat client referenced above creates the thread in response to certain button being clicked, but since you want to start looping as soon as possible I recommend that you create and start the thread in response to the Load event (just double click on the form in designer mode in Visual Studio to create the appropriate load event handler).

    The tricky part is when you want to update a UI element from the background thread. To do this without exceptions you have to marshal the method call to the UI thread. This can be accomplished using the invoke method on any control (again see the referenced sample code).

    To break out of the loop you can set a buttonPressed flag to false in a button clicked event handler. This eventhandler will be run on the UI thread but the shared flag will let the background thread break out of its loop the next time it iterates to the condition statement.

    0 讨论(0)
  • 2020-12-30 16:55

    That's a natural question for someone who's coming from a (completely) different background.

    Programming Windows Forms applications is event driven. When a Windows Forms application starts, a form is loaded (check Program.cs file) and there is a Main loop that is hidden from you to concentrate on the important things in your program.

    You don't need to put anything in the Main loop to respond to an event (like a button clicked event). You just handle the button clicked event by creating an event handler for the Click event of the Button). You can use the designer or do that manually in the code.

    When you create a method to handle an event (and as such the method is called an event handler) it is called automatically when the event is raised/triggered. For example a method handler for the Click event for the Button on your form would be called when the user clicked the button.

    This MSDN topic contains all the information you need: Creating Event Handlers in Windows Forms. If you need more clarification, please ask! :)

    UPDATE: Create an event handler just like above and also create a loop in the Form_Loaded event handler. Be sure to call Application.DoEvents(); inside the loop. This way the event handler for the button click can be handled (in the handler add code to modify a boolean that would make the loop's condition false to cancel the loop).

    UPDATE 2: To make this answer more complete, I mention that you should also consider running the loop on a new thread, not the UI one (and therefore avoid needing to use DoEvents, which has its negatives as my peers pointed out). The following example shows how to create a Thread and cancel it on a Button Click:

        System.Threading.Thread t;
        private void Form1_Load(object sender, EventArgs e)
        {
            //create and start a new thread in the load event.
            //passing it a method to be run on the new thread.
            t = new System.Threading.Thread(DoThisAllTheTime);
            t.Start();
        }
    
        public void DoThisAllTheTime()
        {
            while (true)
            {
                //you need to use Invoke because the new thread can't access the UI elements directly
                MethodInvoker mi = delegate() { this.Text = DateTime.Now.ToString(); };
                this.Invoke(mi);
            }
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            //stop the thread.
            t.Suspend();
        } 
    

    Finally, consider using a BackgroundWorker which encapsulates creating and managing Threads for you.

    0 讨论(0)
  • 2020-12-30 17:01

    Why do you need it to keep looping forever?

    The interesting thing to point out here, is that your program does this anyway; it's called the message loop. It is continuously receiving messages, as the user interacts with it (clicks buttons etc.)

    What are you actually trying to do? There is certainly already a construct that will do what you are looking for, be it a Timer, BackgroundWorker, etc.

    To listen on a TCP socket, there is the TcpListener class. You could fire up a thread for the TCP listener to run in.

    0 讨论(0)
提交回复
热议问题