Where is the appropriate place to start background threads in C# WinForms applications?
I want to start 2 background 开发者_JAVA技巧threads. One thread is acting as a server for a client and another thread is acting as a client for a server. This application is both a server and a client application. Should I start these threads in the Main() function before calling Application.Run()? Or should they be created after the main form is loaded? I'm trying to keep the UI and business logic apart from each other but I know that these threads will need to notify events to the form. What is the best coding practice for this? Thanks!
If they need to perform logic on the main form, you will need that logic to run on the thread the main form was created on. So both the client and server will need to have a reference to the main form so they can call either Invoke or BeginInvoke on it (depending on whether the code on the main form needs to be synchronous or asynchronous). Therefore, you should probably start the threads after the main form is loaded so you can pass a reference to it to the client and server.
Start them at Main()
before the UI is created.
精彩评论