I'm using Visual Studio 2013 and programming in C++ / Xaml. I have a worker thread that splits off from the UI thread to do some calculations. I need this worker thread to be able to access components such as a TextBox or a ProgressBar on the user interface to do things like inform the user on its progress. After some research this is apparently way harder than I anticipated.
You may think the worker threads need to access the UI, but you should re-think that idea, it is a bad approach. You already found out that it is way harder than anticipated - look at this as an indicator that you may be on the wrong track.
The better way is to use indirection, i.e. to post a message, raise an event or signal a flag whenever there are new data available to display. The UI thread handles this and does whatever he needs to do when it is appropriate.
This way you leave room for future improvements, e.g. you may wish to replace the graphical UI by some other version (progress bar instead of a percent label) or a completely different UI later (think web-based, think service without own UI, etc).
Having a worker thread accessing controls directly ties your background worker code too closely to a concrete UI, which is nothing more than an arbitrary restriction that comes with no gain1). By using an indirection (this could be even an properly synchronized view model) you prevent this, making later changes a snap.
1 Who says YAGNI? You already need it, right now!
Related
I am using visual studio 2010 to develop a windows form application using c++.
This program waits for an event like connection request and displays a message
But this program is shown as "not responding" in windows task manager.
Is there any way to make the program appear responsive ??
The standard practice for this situation is to use multi-threading. Create a background thread to wait for the connection request or whatever event you need that might cause the primary thread to block.
This allows the user interface of your application to remain responsive. If you don't use a thread, the primary UI thread will be blocked waiting for the request and can't handle other events such as drawing the form, responding to window events, etc.
In Windows programming, any activity that is going to take a significant amount of time should be threaded. This isn't a hard rule, but a pragmatic amount of threading will make a world of different in giving your application a smooth, responsive feel. The primary thread should be reserved for drawing and handling user interaction.
A Google search will give you plenty of examples, but here is a decent one to get you started.
Sorry I don't know how to phrase this in the title, maybe someone could help me.
I am starting to make a Qt application, let's say, the application will first show N points on the screen. Then we have a function now, called movePoints, when it is called, these points will be moved according to some algorithms.
Now when N is small, everything looks very smooth, it works very well without any problem. But if N is very large, the whole GUI sucks because movePoints is running. So whenever I touch the application window now, it becomes unresponding. But I know lots of programs seem to be able to let the movePoints function run in the back-end (with a progress bar in the status bar or something) without slowing down the main application. How can I achieve this effect?
To keep your application responsive to user interactions, you should use the processEvents function. (http://qt-project.org/doc/qt-4.8/qcoreapplication.html#processEvents)
If you'd rather have the operation occur in the background you can use the QtConcurrent module and use the asynchronous run function (http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html).
Use a QTimer for an interrupt or a QThread to bring the calculation out of the main loop. See: http://qt-project.org/doc/qt-4.8/threads.html
You can use a separate thread to perform calculations in the background without blocking the Qt event loop. See QThread and QConcurrent. It's common practice in processing-intensive Qt applications to have the main thread handle the GUI while "back-end" calculations are done in "worker" threads.
If rendering the data (rather than just calculating the next state) is also an intensive operation, you can also use your worker thread(s) to create a QImage, QGraphicsScene, or similar type of object, and send it pre-built to the UI thread.
If you're limited to a single thread (e.g. your platform doesn't really support threads), then you can take your algorithm and intersperse calls to QCoreApplication::proccessEvents, which will make the GUI more responsive while the activity runs. I find that using actual threads tends to be the simpler and more maintainable approach, though.
I have a GUI app that I am creating with wxWidgets. As part of the functionality, I have to run "tasks" simultaneously with manipulation of the GUI window. For example, I may run the code:
long currentTime = wxGetLocalTime();
long stopTime = wxGetLocalTime() + 3;
while (wxGetLocalTime() != stopTime) {}
wxMessageBox("DONE IN APP");
For the duration of those 3 seconds, my application would essentially be frozen until the wxMessageBox is shown. Is there a way to have this run in the background without the use of multiple threads? It creates problems for the application that I've developing.
I was wondering if there are some types of event handling that could be used. Any sort of help is greatly appreciated.
There are 3 ways to run time-consuming tasks in GUI wx applications:
By far the most preferred is to use a different thread. The explanation of the application being "very GUI intensive" really doesn't make any sense to me, I think you should seriously reconsider your program design if its GUI intensity (whatever it is) prevents you from using background worker threads. If you do use this approach, it's pretty simple but pay special attention to the thread/program termination issues. In particular, you will need to either wait for the thread to finish (acceptable if it doesn't take a long time to run) or cancel it explicitly before exiting the program.
Use EVT_IDLE event to perform your task whenever there are no other events to process. This is not too bad for small tasks which can be broken in small enough pieces as you need to be able to resume processing in your handler. Don't forget to call event.RequestMore() to continue getting idle events even when nothing is happening otherwise.
The worst and most dangerous was is to call wxYield() as suggested by another answer. This can seem simple initially but you will regret doing it later because this can create extremely difficult to debug reentrancy problems in your code. If you do use it, you need to guard against reentrancy everywhere yourself and you should really understand what exactly this function does.
Try this:
long currentTime = wxGetLocalTime();
long stopTime = wxGetLocalTime() + 3;
while (wxGetLocalTime() != stopTime) {
wxYield();
}
wxMessageBox("DONE IN APP");
I know this is late to the game, but...
I've successfully used the EVT_IDLE method for YEARS (back in the 90's with Motif originally). The main idea is to break your task up into small pieces, where each piece calls the next piece (think linked-list). The mechanism to do this is using the CallAfter() method (using C++, of course). You just "CallAfter()" as the last step in the piece and that will allow the GUI main loop to run another iteration and possibly update GUI elements and such before calling your next piece. Just remember to keep the pieces small.
Using a background thread is really nice, but can be trickier than you imagine... eventually. As long as you know the data you're working on in the background won't be touched/viewed by anything else, you're OK. If you know this is the case, then that is the way to go. This method allows the GUI to remain fully responsive during background calculations (resizing/moving the window, etc.)
In either case, just don't forget to desensitize appropriate GUI elements as the first step so you won't accidentally launch the same background task multiple times (for example, accidentally clicking a push button multiple times in succession that launches the background thread).
the application I'm trying to design with Qt is quite data intensive; it is essentially a database. I'm looking for a design that would allow me to keep the UI reactive. My guess is I should keep only the UI in the main thread and create a thread for the database.
However:
- creating a database object inheriting from QThread doesn't seem to be a natural design (what would run() be? )
- I assume I would need to use signals and slots for UI / core interaction; yet this feature seem to be relatively recent in Qt, so I'm wondering if my "design" is wrong.
- QObject descendants are apparently designed to live in the thread in which they were created, so I'm concerned the communication of models (from the database thread) to the UI thread will be problematic.
Thanks for your comments.
You might consider using QtConcurrent::run(). You'll pass in the function you want. It'll spool off a thread to run the function and give you a QFuture that you can use to get the eventual result. You could poll the QFuture to see if it isFinished(). Better, however, may be to use QFutureWatcher which watches the QFuture for you and emits a signal when it's done. See the example code blurb in QFutureWatcher.
Well, I think creating a separate thread for the DB stuff is a good idea... but I would suggest that you only make 1 thread for the DB stuff (not 2, 4, or more). The reason is that unless you are an expert at DB concurrency issues and the locking mechanisms of your DB, things will get complicated.
The thing is that you should not have any other threads mixed with code that has gui or in main of a gui project because any blocking will freeze the GUI as well. So as long as you make a separate DB handler class and thread that, I think you should be OK.
Once I asked that same question "Is this design good?" (after detail explanation), the answer I got is "when doing a design of something, only the sky is the limit".
If you think threads might cause problems, then you should start processes, instead of threads.
Don't forget that you can always block and disable widgets when doing some intensive computation (a famous hourglass icon).
Signals and slots are implementation of observer pattern. In my opinion, it is one of the very useful design patterns. It allows you to easily break dependencies. If you don't like signal slots, then take a look into events.
EDIT
For processes, you can use IPC (inter process communication) - not necessarily using stdout. There are pipes, shared memory and messages.
As for freezing the widgets, you can disable them, or the mouse (turning it into a hourglass) when your application is doing some computation intensive operation, and when you think the GUI might become unresponsive. Or, you can show the invisible widget covering your GUI and change the mouse into the hourglass. This way the mouse events would go to the invisible widget and ignored. You can also add "please wait" box on top of it.
You didn't say what exactly you are trying to achieve. Maybe there is a better way.
I'm having trouble keeping my app responsive to user actions. Therefore, I'd like to split message processing between multiple threads.
Can I simply create several threads, reading from the same message queue in all of them, and letting which ever one is able process each message?
If so, how can this be accomplished?
If not, can you suggest another way of resolving this problem?
You cannot have more than one thread which interacts with the message pump or any UI elements. That way lies madness.
If there are long processing tasks which can be farmed out to worker threads, you can do it that way, but you'll have to use another thread-safe queue to manage them.
If this were later in the future, I would say use the Asynchronous Agents APIs (plug for what I'm working on) in the yet to be released Visual Studio 2010 however what I would say given todays tools is to separate the work, specifically in your message passing pump you want to do as little work as possible to identify the message and pass it along to another thread which will process the work (hopefully there isn't Thread Local information that is needed). Passing it along to another thread means inserting it into a thread safe queue of some sort either locked or lock-free and then setting an event that other threads can watch to pull items from the queue (or just pull them directly). You can look at using a 'work stealing queue' with a thread pool for efficiency.
This will accomplish getting the work off the UI thread, to have the UI thread do additional work (like painting the results of that work) you need to generate a windows message to wake up the UI thread and check for the results, an easy way to do this is to have another 'work ready' queue of work objects to execute on the UI thread. imagine an queue that looks like this: threadsafe_queue<function<void(void)> basically you can check if it to see if it is non-empty on the UI thread, and if there are work items then you can execute them inline. You'll want the work objects to be as short lived as possible and preferably not do any blocking at all.
Another technique that can help if you are still seeing jerky movement responsiveness is to either ensure that you're thread callback isn't executing longer that 16ms and that you aren't taking any locks or doing any sort of I/O on the UI thread. There's a series of tools that can help identify these operations, the most freely available is the 'windows performance toolkit'.
Create the separate thread when processing the long operation i.e. keep it simple, the issue is with some code you are running that is taking too long, that's the code that should have a separate thread.