How to find which process is blocking Android MapFragment UI Thread - mapfragment

Whenever i open an intent, then presses back sometimes give ANR. Which means something is blocking my UI Thread. How to handle this. Can i start my activity on a separate thread. Even though it's a single threaded model

Related

How to Interrupt the UI thread

I'm working on a simulation model that iterates over time steps. At times when the model results start to go South, I want to be able to click on a button to halt the iteration. However, if my testing is correct, when the iteration is running in the UI thread, the Button.Click event is not actuated because the thread is busy iterating. Is that correct? Is there a way to interrupt the UI thread with a button click when the thread is really busy?
One way to handle this problem is to create a Task using the Task Parallel Library to do the computationally-heavy iterations. I'm starting to work on this approach in case there is no way to interrupt the UI thread but I thought I'd check here to make sure I'm not missing a simpler approach.
The problem with your idea to interrupt your calculations on the UI thread is that it requires the cooperation of the UI thread, which is already slammed doing your calculating. For the UI thread to be able to process your button click the calculating needs to stop so the thread can go back to processing UI events. That means saving your progress so you can pick up where you left off later.
This kind of pausing and resuming seems likely to be more trouble than spinning the computation off into its own thread, it is not totally undo-able (the Netscape browser that JWZ developed worked like this, in a single thread), but the reason the multithreaded approach is encouraged is because it's the way that requires the least work, and keeps your calculation code the most focused on the domain and the least chopped up.
If you put the computation in its own thread then the UI thread will be responsive, the OS will make sure both threads get to run. You can make the calculation check for interruption periodically, you can have a progress bar with a cancel button, and you won't have to worry about stopping work to process UI events.
I'm assuming a UI where you have a single event dispatch thread that is responsible for handling UI events. This is how Swing works in Java and it's a popular choice for lots of GUI toolkits because multithreaded solutions are susceptible to deadlocks (events coming from the user will acquire locks in a different order than events coming from the back end). You can specify tags for language and platform to get more relevant answers.

Reasons for not using SendMessage() to access UI controls from other threads?

I have read that SendMessage() should not be used to access UI controls from other threads, but I'm not sure I know why, the only reason that I can think of is since SendMessage() is a blocking call, then it could cause a deadlock in certain situations.
But is this the only reason not to use it?
Edit: This article talks about the reasons not to use SendMessage() but I don't find it to be very clear (it is intended for .NET).
It is best to keep in mind that the odds that you will write correct code are not very good. And the generic advice is don't do it! It is never necessary, the UI thread of a GUI program in Windows was entirely structured to make it simple to allow code that runs on another thread or inside a process affect the UI of the program. The point of the message loop, the universal solution to the producer-consumer problem. PostMessage() is your weapon to take advantage of it.
Before you forge ahead anyway, start by thinking about a simple problem that's very hard to solve when you use SendMessage. How do you close a window safely and correctly?
Given is that the exact moment in time that you need to close the window is entirely unpredictable and completely out of sync with the execution of your worker thread. It is the user that closes it, or asks the UI thread to terminate, you need to make sure that the thread has exited and stops calling SendMessage before you can actually close the window.
The intuitive way to do this is to signal an event in your WM_CLOSE message handler, asking the thread to stop. And wait for it to complete, then the window can close. Intuitive, but it does not work, it will deadlock your program. Sometimes, not always, very hard to debug. Goes wrong when the thread cannot check the event because it is stuck in the SendMessage call. Which cannot complete since the UI thread is waiting for the thread to exit. The worker thread cannot continue and the UI thread cannot continue. A "deadly embrace", your program will hang and needs to be killed forcibly. Deadlock is a standard threading bug.
You'll shout, "I'll use SendMessageTimeout!" But what do you pass for the uTimeout argument and how do you interpret an ERROR_TIMEOUT error? It is pretty common for a UI thread to go catatonic for a while, surely you've seen the "ghost window" before, the one that shows 'Not Responding` in the title bar. So an ERROR_TIMEOUT does not reliably indicate that the UI thread is trying to shut down unless you make uTimeout very large. At least 10 seconds. That kinda works, getting the occasional 10 second hang at exit is however not very pretty.
Solve this kind of problem for all the messages, not just WM_CLOSE. WM_PAINT ought to be next, another one that's very, very hard to solve cleanly. Your worker thread asks to update the display a millisecond before the UI thread calls EndPaint(). And thus never displays the update, it simply gets lost. A threading race, another standard threading bug.
The third classic threading bug is a fire-hose problem. Happens when your worker thread produces results faster than the UI thread can handle them. Very common, UI updates are pretty expensive. Easy to detect, very hard to solve and unpredictable when it occurs. Easy to detect because your UI will freeze, the UI thread burns 100% core trying to keep up with the message rate. It doesn't get around to its low-priority tasks anymore. Like painting. Goes wrong both when you use SendMessage or PostMessage. In the latter case you'll fill the message queue up to capacity. It starts failing after it contains 10000 unprocessed messages.
Long story short, yes, SendMessage() is thread-safe. But thread-safety is not a transitive property, it doesn't automatically make your own code thread-safe. You still suffer from all the things that can go wrong when you use threads. Deadlocks, races, fire-hosing. Fear the threading beast.

Message loop issue using SetParent to embed window into external process

My Windows application has a tabbed interface. Every tab will render some UI stuff. As everyone knows, if I do a very time consuming for-loop in the main thread without let other to process any Windows messages, the application will be frozen. During the frozen period, I cannot switch tabs.
I was inspired by the multiple process architecture of Google Chrome. I try to use SetParent to embed a process into another process. To be more specific: Process A is the master. It can create unlimited worker processes. Every worker process has its own message loop. If process B is frozen, process A and any other worker processes should not be frozen.
Actually I am wrong: If I click a button worker process B to do a lot of UI stuff in main thread without a break, not only the UI of process B but also the UI of process A will be blocked, until my test code ends.
Can somebody share some lights to me?
What you are attempting to do is, er, tricky to get right. I suggest that you start by reading Raymond Chen's article: Is it legal to call have a cross-process parent/child or owner/owned window relationship
Creating a cross-thread parent/child or owner/owned window relationship implicitly attaches the input queues of the threads which those windows belong to, and this attachment is transitive: If one of those queues is attached to a third queue, then all three queues are attached to each other. More generally, queues of all windows related by a chain of parent/child or owner/owned or shared-thread relationships are attached to each other.
This is exactly the scenario that you describe. And the fusing of all the message queues is to be expected. The fact that you have multiple processes doesn't change the fact that you must not block UI threads.
So I think that your program design is flawed. You are adding an epic amount of complexity, with no reward. The benefits of a multi-process architecture are security and isolation. You don't change anything with regards to blocking UI threads. The only way to solve your problem is to put the long running task on a non-UI thread. My strong advice is to return to a single process design.

Intervening threads that waited for too long

Is there anyway in F# that I can detect if a current waiting thread is waiting for too long without being contacted?
I have a case where threads must be actively contacting other waiting threads to pass their work to once they're finished. My solution is having a bug somewhere that sometimes one or more threads just wait for too long and eventually the program got deadlocked because other threads don't contact them.
I think by detecting if a waiting thread is simply waiting for too long, it will just actively go looking for available work, rather than keeping waiting for other threads to pass to it.
It's probably better to try and understand why your threads are getting stuck than just terminating them. If you can reproduce this with the Visual Studio debugger attached, you can click the Pause button and use the Threads window to see what code all threads are in.
That said; if you still have the need to do this, the solution will depend on how you're managing your threads. To monitor them from the outside, you'll need some process that has a list of threads and the ability to tell whether they're dead.
The Thread class doesn't appear have any built-in mechanism for sharing state between the thread and its control except for Name. You could possibly abuse name, but I would probably have a thread-safe collection (eg. a ConcurrentDictionary<Thread, DateTime>) to store all of the threads and the timestamp of their last communication, and pass an Action into each thread when it's started that allows it to "Ping" by calling the action periodically. The action would simply update the DateTime stored against that thread.
The controlling process then simply scans through the dictionary periodically for anything with a timestamp that is too old, declares that thread dead and Aborts() it.
It's hard to give a code sample without knowing exactly how you're spawning your threads and describe what a thread "being contacted" means in more detail.

Can you receive Events in a secondary thread in Delphi XE?

I would like to have three threads in a sample application.
Thread #1 (Main Thread) - User Interface/GUI
Thread #2 - Tied to a serial port device receiving data via events passing to a data queue.
Thread #3 - Activated when a queue entry is made, process data node, frees data object.
The goal is to
a) Prevent the loss of data when a button or the form is held by the mouse on the main form.
b) Quickly get the data from the event, stuff it in the queue, go back to sleep
c) Process data when we have it, otherwise sleep.
Can packages like AsyncoPro tie event handling to a non-main thread?
I've never done much with serial port event driven apps, most of what I've work with are polled and I want to do some testing.
You can definitely tie event handling to a non-main thread. What you can't do is tie screen updating to a non-main thread. The Windows API is not threadsafe, and so the Delphi VCL, which is built on top of the Windows API, isn't either. But your design is basically a good, workable idea; just remember to use the Synchronize or Queue methods of TThread to send any UI updates back to be executed on the main thread.
The easiest should be to define some user messages, then sent it from sub-threads to the main thread.
It's perfectly thread-safe, and even process-safe.
Use PostMessage() with the Handle of the main form. But don't broadcast this WM_USER+n message to the whole UI, because you could confuse some part of the VCL which defines its own custom messages.
If you want to copy some textual data accross threads or processes, you can see WM_COPY_DATA. In practice, this is very fast, faster than named pipes for small messages.
For User Interface, I discovered than a stateless implementation is sometimes a good idea. That is, you don't call-back the main thread via a Synchronize() call or a GDI message, but your main GUI thread has a timer which check a shared memory buffer for pending updates. This is how the web works, and in practice, it's pretty easy to work with: you don't have to write any callback, each thread is independent, do its own stuff, and refresh when necessary.
But of course, the solution depends on your exact project architecture.
For a simple but proven library, see AsyncCalls, working from Delphi 5 up to XE. For latest versions of the IDE (Delphi 2007 and later), take a look at OmniThreadLibrary. By using such libraries, you'll ensure that your software implementation won't break anywhere: it's very common for a multi-threaded application to work as expected most of the time, then, for unknown reasons, going into an endless loop. And, of course, it happens only on the customer side, not yours... If you don't want to spend hours debugging your program, just trust those proven libraries, which are known to be well designed and debugged.
Sure you can do this, one way or another. Not used Apro since D5 - the Apro I have does not work on my D2009, (unicode/string/ANSIstring issues), & I have my own serial classes. Most of the available serial components have the option of firing dataRx events on either the rx thread or the main GUI thread - obviously in your case you should select the rx thread, (Thread #2). Shove the rx data into some buffer class and push it onto a producer-consumer thread to (Thread #3). Process it there. If you need to do a GUI update from there, PostMessage the reference to the GUI thread and handle it in a user-defined message-handler procedure.
Done this sort of stuff loadsa times - it will work OK.
Rgds,
Martin

Resources