Here is my target: the app consists of an form – MainForm – which contains a lot of tabs (Notepad++ GUI-like). Each tab is an UserControl descendant (UCDx). MainForm can display 2 or more tabs which contain instances of the same UCDx. The target is that UCDx will have to perform some time-consuming actions or method executions – i.e. DB read/write, Web Service methods calls. This kind of actions I’d want to run in separate threads, in order not to freeze UI. Also I’ll need to implement an info form (InfoForm) – which will show info upon current running threads, with some interaction functionality – i.e. close threads that runs too long.
The main problems I faced are:
- thread interaction with GUI – i.e. an thread reads data which should be displayed in a grid;
- thread interaction managing – upon implementing InfoForm.
In concurent/paralel programming I’m beginner – can someone give some clues upon how to implement that?
I would first separate your worker logic from the UI.
For example, for a “thread which needs to read data and display it”, try to split your problem into smaller pieces:
Create a plain class which has a synchronous processing method, no threading involved. Something like:
Test it. Create unit tests, or even a small console app where you can see that it works fine without a GUI.
Create an async wrapper class, which calls the
ServiceReaderto do the job, but calls it on a background thread, and fires an event when done.Again, test it. This should be a separate class library, independent of your GUI.
Use MVC or similar pattern to separate your views (tabs) from your model (async service reader). This means you should fire interaction events from your views, handle them in controller, and then let controller call the appropriate action in the model:
Finally, make sure that background thread calls get dispatched to the right (GUI) thread. This would simply mean your tab view needs to check if invoke is required:
Separating the model from the view will simplify testing, and later changes to UI. You may decide to make this a console app, or a windows service, and this will keep your business logic intact.