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
- Use BackgroundWorker
- Use Control.Invoke
- Use SynchonizationContext
- Use Task Parallel Library (
System.Threading.Tasks
) - Use Rx
- DO NOT USE Thread.Start or ThreadPool
精彩评论