Xamarin async Method on Main Thread clarification - xamarin.forms

Does .ConfigureAwait(false) always use the thread pool and not the UI thread
or is just a hint?
This is a question that has bugged me and I haven't heard a definitive answer.
So is it possible even if you do a .ConfigureAwait(false) block the main UI thread and when debugging the dreaded
Skipped 100 frames!!
message?

Using .ConfigureAwait(false) means when that task ends, the following code will not be marshaled back to the calling thread, saving some thread marshalling, which takes time. When .ConfigureAwait(false) is not called the default is .ConfigureAwait(true) which means "When this task is done, marshal the following code back to the thread this task was called from.
As a general rule, every piece of code that is not in a view model and/or that does not need to go back on the main thread should use ConfigureAwait false.
This is simple, easy and can improve the performance of an application by freeing the UI thread for a little longer.
It is not only a matter or performance but also a matter of avoiding potential deadlocks.
you could read this document

Related

QObject deleteLater after QThread quit

I want to design a single base class for both controlling the thread and executing slots of the class in thread itself via qobject::connect or invokemethod.
When start is called, I call this->movetothread(memthread) and memthread->start to move this into member thread's context and start the eventloop.
when stop is called, qthread's quit is called to stop the event loop. Problem is that, when thread quits, it is impossible to deallocate "this" via deletelater later on since deletelater needs a running eventloop to delete the object. Object's thread context could already be stopped via call to quit before.
I can't connect object->deletelater to thread::finished since object would be unusuable then and I can't start/stop thread again. My aim in the design is to accomplish this actually. Being able to stop the thread, start later, stop again and so on.
I'm not sure if the design is doable with the way qt is but want to at least try.
P.S. My first question, please kindly let me know about any mistakes.
I am not sure I understand the question completely, and also there are very few details. However, why stopping the thread in the first place? Anyway, depending on the specific context, you could start the thread when you want to delete your object and then delete it, then stop the thread and delete the QThread. Otherwise you could simply delete your object. Anther option is to move your object to the main thread when stopping your thread:
QMetaObject::invokeMethod(this, [this] {
moveToThread(qApp->thread());
});
and then simply deleteLater() when you feel you are ready. These are two options, but I think there are others, it depends on your context.

Is it possible to re-paint/update content in a Qt GUI application although the main thread is blocked?

There is a lot of discussion (e.g. here) going on about spinning or moving busy indicators in a GUI but I could not find a single one that clearly states that it is impossible to re-paint/update any content in a GUI application while the main thread is blocked.
This question is actually a general one and is not necessarily directly related to Qt GUI applications.
When the main thread of a GUI is performing a blocking operation no events are processed and no content can be re-painted. There are two "recommended" approaches:
Using worker threads
Splitting the work in chunks and updating the UI "just not that often"
The problem is that there are operations that simply cannot be moved to worker threads or any other asynchronous mechanism. The best example is the serialization and de-serialization of the UI itself. In both scenarios the user must not click happily in the UI and change settings while the settings, properties, etc. are taken from the widgets (during the saving) or applied to the widgets (during the loading). This is true for the threading approach as well as the splitting into chunks.
Edit: Another example is the application of stylesheets to a complete GUI. Imagine that a user wants so select a "dark" scheme. All of the widgets need to be updated and the currently visible ones needs to be re-painted. During this step the event loop cannot run. A similar discussion can be found here.
In my case I'm working on an embedded device so there is another approach:
Directly overwriting a specific region of the framebuffer
This approach feels very ugly and comes with a lot of problematic scenarios and surly involves lots of debugging.
The last but sad approach:
Do not use any moving/updating content at all and just show something static such as "...in progress..."
Well, this is just sad...
Do you agree on these observations? Does anyone know of a different approach or concept in general un-related to Qt?
The problem is that there are operations that simply cannot be moved to worker threads or any other asynchronous mechanism.
I can't agree. These operations should be split into blocking and non-blocking operations. Everything that blocks should be handled asynchronously, or, if no non-blocking APIs are available, handed off to a worker thread.
The best example is the serialization and de-serialization of the UI itself.
I find it a particularly poor example mainly because I've yet to run into a need for blocking the GUI, and serialization doesn't call for it.
In both scenarios the user must not click happily in the UI and change settings while the settings, properties, etc. are saved or loaded.
Construction and destruction of the widgets should be very quick, if that's what you mean by "deserializing" the UI. Recall that the blocking I/O and long parsing has been done in another thread. Almost all Qt widgets certainly are quick to set up, and those that are not are a necessary evil that you have no choice but to live with. If you have your own widgets that do blocking operations like disk or registry access in their constructors or event handlers (plenty of such "code" exists), fix them.
If you're merely talking about setting widget values, this again is super-quick and can be done all in one batch. You will probably need a viewmodel to asynchronously interface between the view (widgets, QML view, or a QAbstractItemView) and the data source.
Disk I/O and parsing/output of the on-disk representation belongs in a separate worker. Once you create an internal representation, it can be passed to the gui thread to build the widget tree or populate the interface.
You should implement thread-safe models using QAbstractItemModel or a similar interface, and populate them in a worker thread, and let the GUI thread react to the updates in real time.
If you wish to indicate to the user that a part of the interface is not usable yet, e.g. while a model gets populated, you could do so via an overlay, making sure that you temporarily disable the focus on the widgets that are under the overlay. This is not hard and I'd find it amusing if your entire question could be reduced to "how do I make a part of the UI inaccessible while it's being modified".
The key thing missing is that the UI should handle asynchronously reacting to a model changing its state. For all I care, it could take an hour to load the data needed to fully populate the model. It doesn't mean that your application should be unresponsive. Simply make the parts of the UI that can't be interacted with inaccessible for interaction. Ensure that other parts of the application that need the configuration data are similarly either inaccessible or in a partially usable state that will asynchronously revert to full state once the configuration becomes available.

Is asynchronous a kind of concurrency

I already know when calling an asynchronous method e.g. myAsync(), the caller e.g. Caller() can continue executing without waiting for it to be finished. But on the other hand, myAsync() also is executing.
public void Caller(){
myAsync();---------------------running
dosometing();------------------running
}
The code next to myAsync() in Caller() will execute with myAsync() at the same time. So could this situation be considered as a kind of concurrency?
update
I prefer use javascript and c#
That very much depends on the concurrency model of your programming language.
If your language allows you to define methods that are "implicitly" running in parallel; then of course, calling myAsync() would use some kind of "concurrency mechanism" (for example a thread) to do whatever that method is supposed to do.
In that sense, the answer to your question is yes. But it might be important to point out that many "common" programming languages (such as Java) would only "work" in such a context when myAsync() would be creating some thread to then run "something" using that thread.

How can I find out when a PyQt-application is idle?

I'd like to know when my application is idle so that I can preload some content. Is there an event or something similar implemented in PyQt?
(I could also do it with threads, but this feels like being too complicated.)
You have at least two different options, you can use a thread or use a timer. Qt's QThread class provides a priority property that you can set to make it only process when no other threads are running, which includes the GUI thread. The other option is a single shot timer. A QTimer with a timeout of 0 milliseconds puts an event on the back of the event queue so that all events and synchronous functions already active or scheduled will be processed first.
In code, the two options would look like the following:
// (1) use idle thread processing
MyQThreadSubclass idleThread;
idleThread.run(QThread::IdlePriority);
// (2) use QTimer::singleShot
QTimer::singleShot(0, receiver, SLOT(doIdleProcessingChunk));
If you go with the single shot QTimer, be careful how much processing you do as you can still block the Gui. You'd likely want to break it into chunks so that GUI won't start to lag:
// slot
void doIdleProcessingChunk() {
/* ... main processing here ... */
if (chunksRemain())
QTimer::singleShot(0, receiver, SLOT(doIdleProcessingChunk));
}
Obviously, the above is C++ syntax, but to answer with respect to PyQt, use the single shot timer. In Python, the global interpreter lock is basically going to render much of your concurrency pointless if the implementation being called is performed within Python.
You also then have the choice of using Python threads or Qt threads, both are good for different reasons.
Have a look at QAbstractEventDispatcher. But ... I still suggest to use a thread. Reasons:
It will be portable
If you make a mistake in your code, the event loop will be broken -> You app might hang, exit all of a sudden, etc.
While the preloading happens, your app hangs. No events will be processed unless you can preload the content one at a time, they are all very small, loading takes only a few milliseconds, etc.
Use a thread and send a signal to the main thread when the content is ready. It's so much more simple.

Flex equivalent of ProcessMessages and unresponsive UI during long loops

I find that my Flex application's UI becomes unresponsive during very long processing loops (tens of seconds). For example, while processing very large XML files and doing something per-element...
Is there an equivalent of "ProcessMessages"? That is, a call that would tell Flex to continue responding to UI events, even in the middle of some long loop, so that the UI doesn't become unresponsive?
I'm aware Flex is single threaded by design. That's exactly why I'm looking for something like ProcessMessages() - a function that allows single-threaded reentrant applications (like in VB, or single-threaded message loop based C++ applications) to remain responsive during long operations.
Summary of Answers
There's no built-in function like HandleEvents() or ProcessMessages() in Flex.
Using some sort of callback mechanism to iteratively process chunks of a long computation process, while yielding to the runtime between chunks, thus enabling it to be responsive, is the only way to maintain a responsive UI during long computations.
Ways of accomplishing the above are:
Using the enterFrame event, which is called whenever the Flash "movie" layer below the Flex application refreshes its frame (which is something like 20fps).
Using a timer.
Using UIComponent.callLater() which schedules work to be done "later". (as the docs say: Queues a function to be called later. Before each update of the screen, Flash Player or AIR calls the set of functions that are scheduled for the update.
Using intentionally triggered mouse/keyboard events to create pseudo "worker threads", as in this example.
If there are further suggestions, or if I left out anything, please feel free to edit this (now) wiki piece.
The problem is that Flash is single threaded, i.e. until a part of the code is running, no other processing can be made. You'll somehow need to break up the processing into smaller chunks and execute these chunks, say, on the enterFrame event.
Edit: I'm afraid that downvoting this (or Simon's) answer does not change the fact that this is not doable in AS3. Read this article for more insight on the problem. The article also includes a simple "library" called PseudoThread, which helps in executing long background computations. You still have to break up the problem into smaller pieces yourself, though.
I can tell you definitively that as of Flex 3, there is no built-in construct similar to the ProcessMessages functionality you are describing.
The most common way to work around this is to split whatever work you are processing into a queue of "worker" tasks and a "worker manager" to control the queue. As each "worker" completes its processing, the worker queue manager pops the next worker off the queue and executes it in a callLater() invocation. This will have an effect that is similar to "yielding to the main thread" and allow your UI to receive events and be responsive, while still allowing the processing to continue when control is returned to the worker.
Once you've got this working, you can do some testing and profiling to figure out if your application can get away with executing a run of multiple workers before invoking callLater(), and encapsulate this logic within the worker queue manager. For example, in our implementation of this pattern (with a few hundred workers in the queue), we were able to get the processing done more quickly with a comparable perceived performance by executing 4 workers before "yielding to the main thread" with callLater(), but this is totally dependent on the scope and nature of the work that your workers are doing.
The process model for ActionScript is single threaded, so the answer is no. Best bet is to either defer to an asynchronous task on the server if you can, or pop up a wait cursor while your long loop runs, or break your process into some smaller pieces which are not quite as intrusive to the UI, or perform the long running tasks at a moment when the user is less likely to feel the effect (app startup for instance).
Actionscript is single threaded by design, no amount of downvoting answers will change that.
For compatibility your best bet is to try to split up your processing into smaller chunks, and do your processing iteratively.
If you absolutely need threading it can sort of be done in Flash Player 10 using Pixel Bender filters. These will run on a separate thread and can give you a callback once they are done.
I believe they are well suited for "hardcore" processing tasks, so they might fit your purpose nicely.
However, they will put a whole other set of demands on your code, so you might be better of doing small "buckets" of computing anyways.
There is no equivalent functionality in Flash Player. By design, Flash Player alternates between rendering to the screen and then running all of the code for each frame. Using Event.ENTER_FRAME events on display objects, or Timer objects elsewhere, are the best bet for breaking up very long calculations.
It's worth noting that some events in ActionScript have an updateAfterEvent() function with the following description:
Instructs Flash Player or the AIR runtime to render after processing of this event completes, if the display list has been modified.
In particular, TimerEvent, MouseEvent, and KeyboardEvent support updateAfterEvent(). There may be others, but those are the ones I found with a quick search.

Resources