开发者

How do you make threaded GUI applications in WinForms correctly?

I'm from C background, and currently I want to make a small WinForms utility that has responsive GUI, and long running worker thread.

GUI is regular Form1 derived stuff, with progress indicators and stuff, worker thread is of kind new System.Threading.Thread();.

In C++ everything is simple, in .NET I have no clue what to do.

Is there a PostMessage kind of w开发者_JS百科ay for data updates? Do I kick a Timer on the main thread that reads shared lock protected structure, is there another approach? Saw multiple documents on delegates, but after 10 different articles they doesn't seem to work, maybe because I have a Worker<->GUI relation, not a GUI<->GUI relation.

All GUI stuff is in GUI class, all worker stuff is in its own worker class. What are the best practices in managed world?


There are many ways, but simply,

  • Launch a thread
  • Use InvokeRequired and Invoke() to get back to GUI Thread

Also BackgroundWorker provides an easier approach.


this is the program class in WinForms Application

 static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }

here there is only a single thread [STAThread]

you can use [MTAThread]instead of it so multiple threads can be handled

or can create thread a runtime using System.Threading


  1. Use BackgroundWorker
  2. Use Control.Invoke
  3. Use SynchonizationContext
  4. Use Task Parallel Library (System.Threading.Tasks)
  5. Use Rx
  6. DO NOT USE Thread.Start or ThreadPool
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜