A question about Thread.Sleep inside backgroundworker - backgroundworker

As far as I understand backgroundworker in .Net runs on a separate threat than in GUI. And Thread.Sleep is not recommended since it freezes the GUI.
Now if one uses Thread.Sleep inside backgroundworker's DoWork, would GUI freeze or this time Sleep will only sleep the BW's thread? Is it still not recommended?
(I tried to give 1 second pauses inside DoWork by Thread.Sleep(1000) seems it doesnt interfere with GUI. Is there another way to give pause inside BW rather than Thread.Sleep? await Task needs sync method which BW is not:()

Now if one uses Thread.Sleep inside backgroundworker's DoWork, would GUI freeze or this time Sleep will only sleep the BW's thread?
Thread.Sleep, like all other methods, runs on the current thread. So Thread.Sleep causes the current thread to sleep. If it's called from the BGW's DoWork, then it will cause the BGW's thread to sleep.
Is there another way to give pause inside BW rather than Thread.Sleep?
No, but you could replace the BackgroundWorker completely with Task.Run, and then you could use await Task.Delay instead of Thread.Sleep.

Related

How to make sense of Kotlin coroutines?

I have tried reading various tutorials and pages on Kotlin coroutines and even though it kind of makes sense to me, I still don't feel it has clicked and I dont feel ready to jump on writing async non-blocking code with coroutines. I think what i am missing is a diagram or picture of what exactly happens and in what order when a piece of coroutine code executes. How does that code run at the thread level?
launch {
delay(1000)
println("World (${currentThread().name})")
}
println("Hello (${currentThread().name})")
sleep(1500)
My understanding is this. I am happy to be corrected or given a different example to further my understanding.
Line0: Code starts on main thread
Line1: Launches a new coroutine on a new thread (from forkjoin pool i suppose)
Line2: Suspending function so the coroutine suspends and returns the thread to the thread pool (hence being non-blocking)
Line5: Prints on the main thread
Line6: Blocks the main thread for 1.5s
Line3: The coroutine resumes execution on (not sure which thread here - same as the thread before suspension or can be a different thread?). The coroutines prints on that thread and finishes, hence returning the thread to the pool again.
Another question i have is how would the low-level execution change if i wrap the whole code around runBlocking { ... }
Your code doesn't actually do anything that would reveal the special nature of coroutines. It makes two threads do their thing concurrently, just as they would do it in plain Java.
It only gets interesting when you launch a coroutine on the same thread you're already on (for example, the main thread). This is one of the things you achieve with a runBlocking block:
runBlocking {
launch {
delay(1000)
println("Hello from the launched coroutine. My thread is "
+ Thread.currentThread().name)
}
println("Hello from the top-level coroutine. My thread is "
+ Thread.currentThread().name)
}
This will print
Hello from the top-level coroutine. My thread is main
Hello from the launched coroutine. My thread is main
runBlocking runs an event loop on the calling thread and propagates a reference to it to all the coroutines you launch within it. For example, delay(1000) will post an event to this event loop, with an indicated delay of one second, and then it will suspend the coroutine. This will allow the main thread to run the rest of the code below launch. When the time elapses, the event loop will run the event handler, which will in turn resume the coroutine.
An even more educational example is launching a coroutine without any Dispatcher. This removes the illusion of coroutines looking like threads and reveals their true magic: by calling continuation.resume() you make the current thread jump right into the middle of the suspended coroutine's block of code, and all that happens using plain Java method calls. I suggest studying this answer where this is explained in detail. If you're interested in an even more in-depth explanation of how plain Java methods can do this trick, I suggest you watch Roman Elizarov explaining this on YouTube.
Here is another example metioned here: https://kotlinlang.org/docs/reference/coroutines/basics.html#your-first-coroutine
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
The above code prints:
Hello,
World!
As you can see, although the code looks synchronous, the execution is asynchronous. That's the whole idea of Coroutine.

How to change tab while progress bar is being updated in QT

I have a Qwidget with a few tabs. In one of the tabs, after clicking a button, a function starts processing data and updates a progress bar.
I'd like to be able to change tabs while this process is running, currently it does'nt let me do so. Any idea?
(1) You must use a modeless progressdialog insteal of modal one. Practically, the main event loop must get the control to allow user interaction.
http://www.bogotobogo.com/Qt/Qt5_QProgressDialog_Modal_Modeless_QTimer.php
(2) You should put your data processing function to worker thread and invoke a progress dialog update to main UI thread from that. That way your task would not block UI, so you could interact with the window (like changing tab) meanwhile.
Qt also provides means to implement this, you might want to refer to:
QFuture, QtConcurrent::run(): run a task in separate thread.
QFutureWatcher: help monitor the progress of a task running in worker thread.
Example:
http://doc.qt.io/qt-5/qtconcurrent-progressdialog-example.html
Below logic may help you.
You can achieve this by using QThread.
Move the process to a separate thread(assume as worker thread)
So now there will be two thread (1. main thread & 2.worker thread)
Execute the process from worker thread
Use signal & slot mechanism to communicate between the main thread(1) & worker thread(2) (to update GUI and or to do some process)
This logic will stop the application from getting hanged.
Refer this link to know in detail.
You can get the sample application here, which follow the above said logic
Application screen shot :
Start Progress(Thread) : Start the thread and do process
Stop Process (Thread) : Stop the thread

Qt to update (repaint) textbox while processing

My Qt 4 application can only update the log box area (actually the whole GUI) until a function finishes execution. Is there any way to update the GUI/log box during the execution? Like adding something like QWidget::repaint() or QWidget::update() in the for loop, so the user can see that the GUI is processing, rather than wait until the function finishes and print out the log at once.
You need to occasionally call QCoreApplication::processEvents() during the execution of your function. This will keep the GUI alive and responsive by letting the event loop run.
An alternative is to execute your function in a separate thread. More information on threads in Qt can be found here: http://qt-project.org/doc/qt-4.8/threads.html.

Qt: setting an override cursor from a non-GUI thread

A while ago I wrote a little RAII class to wrap the setOverrideCursor() and restoreOverrideCursor() methods on QApplication. Constructing this class would set the cursor and the destructor would restore it. Since the override cursor is a stack, this worked quite well, as in:
{
CursorSentry sentry;
// code that takes some time to process
}
Later on, I found that in some cases, the processing code would sometimes take a perceptible time to process (say more than half a second) and other times it would be near instantaneous (because of caching). It is difficult to determine before hand which case will happen, so it still always sets the wait cursor by making a CursorSentry object. But this could cause an unpleasant "flicker" where the cursor would quickly turn from the wait cursor to the normal cursor.
So I thought I'd be smart and I added a separate thread to manage the cursor override. Now, when a CursorSentry is made, it puts in a request to the cursor thread to go to the wait state. When it is destroyed it tells the thread to return to the normal state. If the CursorSentry lives longer than some amount of time (50 milliseconds), then the cursor change is processed and the override cursor is set. Otherwise, the change request is discarded.
The problem is, the cursor thread can't technically change the cursor because it's not the GUI thread. In most cases, it does happen to work, but sometimes, if I'm really unlucky, the call to change the cursor happens when the GUI thread gets mixed in with some other X11 calls, and the whole application gets deadlocked. This usually only happens if the GUI thread finishes processing at nearly the exact moment the cursor thread decides to set the override cursor.
So, does anyone know of a safe way to set the override cursor from a non-GUI thread. Keep in mind that most of the time, the GUI thread is going to be busy processing stuff (that's why the wait cursor is needed after all), so I can't just put an event into the GUI thread queue, because it won't be processed until its too late. Also, it is impractical to move the processing I'm talking about to a separate thread, because this is happening during a paint event and it needs to do GUI work when its done (figuring out what to draw).
Any other ideas for adding a delay to setting the override cursor would be good, too.
I don't think there is any other way besides a Signal-Slot connection going to the GUI thread followed by a qApp->processEvents() call, but like you said, this would probably not work well when the GUI thread is tied up.
The documentation for QCoreApplication::processEvents also has some recommended usages with long event processing:
This function overloads processEvents(). Processes pending events for
the calling thread for maxtime milliseconds or until there are no more
events to process, whichever is shorter.
You can call this function
occasionally when you program is busy doing a long operation (e.g.
copying a file).
Calling this function processes events only for the
calling thread.
If possible break up the long calls in the paint event and have it periodically check to see how long it has been taking. And in any of those checks, have it set the override cursor then from in the GUI Thread.
Often a QProgressBar can go a long way to convey the same information to the user.
Another option that could help quite a bit would be to render outside of the GUI thread onto a QImage buffer and then post it to the GUI when it is done.

Can I use QwaitCondition.wait() in a slot called by the main thread?

if the maximum wait time is 10 ms can i use qwaitcondition in Qt's main thread?
Nothing stops you from using QWaitCondition in the main thread. If you are setting the wait time to 10ms, and it passes without unlocking you will probably not get the desired effects you want. The default is to wait indefinitely.
However, using a wait condition in the main thread will cause the GUI to become unresponsive while it waits. This is almost always undesired.

Resources