Looping Forever in a Windows Forms Application

后端 未结 4 542
误落风尘
误落风尘 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: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.

提交回复
热议问题