Freeing a component from Thread in Delphi - multithreading

I have written a thread to check if there are any freeze in mainform. I am doing this because sometimes TWebbrowser freezes main UI. I think it is because of a javascript and i can not reproduce this problem.
What i need is to safely stop TWebbrowser's job. Actually it should be in a loop or waiting for something but it freezes somehow. Well what i need is to detect and kill the browser and recreate it.
This is how i detect the freeze:
bFreeze := SendMessageTimeout(hwn, WM_NULL, 0, 0, SMTO_ABORTIFHUNG OR SMTO_BLOCK, TIME_OUT, iRes) <= 0;
Any advice will be greatly appreciated.
Thanks

You are running the browser control from your program's main thread. Any attempt to forcibly terminate the browser thread will bring down your entire program. If you have code that can hang, and you wish to recover from that, then it is just not realistic to expect to run that code from your main thread.
Modern browsers deal with this problem by isolating each page in a distinct process. Then if that page hangs in some way, or crashes, the page process can be killed without impacting on the other pages open in the browser.
If you really want to have similar robustness you'll need to have a similar architecture. You might be tempted to think you can isolate a page in a thread within a single process but in practise this doesn't give sufficient isolation.
Perhaps a more tenable solution is to avoid the hang in the first place. Maybe you need to make sure that you are using the latest browser engine. Did you specify that in the browser feature emulation registry key?

Related

WebControl in a separate process stealing focus revisited

I need to process AJAX in my crawler and would prefer using system browser albeit I may have to change my mind. My crawler program may generally be working in background while the user can work on other stuff in other applications.
Anyhow - since WebControl leaks memory if processing JS libs that leak memory - this can cause a crawler to quickly run out of memory. (Many SO posts about this.)
So I have created a solution that uses a separate "dummy" small executable with the webcontrol that takes input/output. This is launched as a separate process by the crawler. This part seems to work great. This child process is created/destroyed as many times as needed.
However, this called process with the embedded-IE grabs focus on every page load (a least if e.g. JS code calls focus) which means if the user is doing work in e.g. Word or whatever - keyboard focus is lost.
I have already moved the embedded IE window off-screen, but I can not make it invisible in the traditional sense since then the embedded IE stops working.
I have tried to disable all parent controls before calling navigate - but it does not work for me.
Any ideas I have not tried? Maybe somehow catch a windows message that focuses webcontrol and ignore it? OR something so I can immediately refocus the earlier control that had focus?
I currently use Delphi - but this question is applicable to VB, C# .Net etc. from my earlier investigations on this matter. I will take a solution and ideas in any language.

wxpython using gauge pulse with threaded long running processes

The program I am developing uses threads to deal with long running processes. I want to be able to use Gauge Pulse to show the user that whilst a long running thread is in progress, something is actually taking place. Otherwise visually nothing will happen for quite some time when processing large files & the user might think that the program is doing nothing.
I have placed a guage within the status bar of the program. My problem is this. I am having problems when trying to call gauge pulse, no matter where I place the code it either runs to fast then halts, or runs at the correct speed for a few seconds then halts.
I've tried placing the one line of code below into the thread itself. I have also tried create another thread from within the long running process thread to call the code below. I still get the same sort of problems.
I do not think that I could use wx.CallAfter as this would defeat the point. Pulse needs to be called whilst process is running, not after the fact. Also tried usin time.sleep(2) which is also not good as it slows the process down, which is something I want to avoid. Even when using time.sleep(2) I still had the same problems.
Any help would be massively appreciated!
progress_bar.Pulse()
You will need to find someway to send update requests to the main GUI from your thread during the long running process. For example, if you were downloading a very large file using a thread, you would download it in chunks and after each chunk is complete, you would send an update to the GUI.
If you are running something that doesn't really allow chunks, such as creating a large PDF with fop, then I suppose you could use a wx.Timer() that just tells the gauge to pulse every so often. Then when the thread finishes, it would send a message to stop the timer object from updating the gauge.
The former is best for showing progress while the latter works if you just want to show the user that your app is doing something. See also
http://wiki.wxpython.org/LongRunningTasks
http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
http://www.blog.pythonlibrary.org/2013/09/04/wxpython-how-to-update-a-progress-bar-from-a-thread/

google chrome has multiple processes , what about UI threads?

I have always read and worked off a single UI thread since having more than one will screw up message pumping etc etc.
I am answering my own question here but want to validate my understanding on Chrome browser which is known to have multiple processes ( one per tab ) - does it also accelerate some bit on the rendering part by employing multiple UI threads ?
My guess is it does NOT , but if it does It would be very interesting to know or look at some sample c# code to demo the same ( does not have to be web browser demo).
Any pointers in the multiple UI thread direction would help! thanks.
I cant state definitively how Chrome handles the rendering threads - but I would assume that each tab has its own rendering thread. I wouldnt see the point of going through all the effort of process isolating the tabs, only to tie them all together on a common rendering thread. They would all have the opportunity to interfere with each other.
I implemented a 'chrome-style' browser using WPF - the application shell was a single process, then each 'tab' was a MAF AddIn running in a separate process. The rendering was all in child processes - there was nothing shared. Each AddIn returned an INativeHandleContract (a WPF control) which was passed across the process boundary.
The upshot of this, was that an exception ANYWHERE in a child tab, would only take down the tab, and could be detected by the parent process, giving it a chance to provide some feedback/reload the tab etc.
This document wasnt around when I achieved it, but after a quick browse I think it has some pointers:
http://msdn.microsoft.com/en-us/library/bb909794.aspx
Kent Boogaart also lent a helpful hand
http://kentb.blogspot.com/2008/06/maf-gymnastics-service-provider.html
You may also need this QFE from Microsoft to fix a bug in serialization you may experience when passing a WPF control across a process boundary:
http://archive.msdn.microsoft.com/KB982638
In regards to MS Connect bug: https://connect.microsoft.com/VisualStudio/feedback/details/467381/wpf-controls-cannot-be-passed-across-process-boundaries
Don't confuse threads and processes. Each process will have it's own ui thread, but likely also it's own message pump.

Outputting console data from a process to gui in wxwidgets

I'm running a long process in the background. I've managed to output the console data to gui. But the problem is that, the data is returned only after the process is finished. But I need to display the data at realtime. ie, I need to display the data, every time it produces some output on the console. I'm running the process with in my gui from a seperate thread.
I mean, it would be like building a gui for the ping command, where output is displayed on console after each packet is send, ie at realtime. I just need to redirect that to gui, in realtime. I'm implementing the gui in wxwidgets. Any help would be greatly appreciated.
Thanking You..
Jvc
Is the output you wish to display generated in a separate process from the process running the GUI? Or in a separate thread in the same process?
I ask because most people, when they ask this question, mean a a separate thread. Since you have tagged your question with "process" I will assume that is what you mean.
You need some inter-process communication. There is a bewildering variety of techniques to do this. Personally, I always use sockets.
wxWidgets has simple, easy to use socket classes wxSocketClient and wxSocketServer.
The background process is probably not running wxWidgets, so you will need something else there. I reccomend boost::asio. I know it looks intimidating, but in fact the tutorial code can be used as is.
There is a lot more to be said, but I risk straying away from the point, since there are so few details in your question.
You can have an output queue protected by a wxMutex. The thread doing the computation writes to the queue, then signals the GUI thread using wxQueueEvent with a custom event to let it know that the thread is not empty. The GUI thread then reads the queue and outputs the data.

Which is the correct way to wait for a Thread.finalization and keep my application responsive

Actually i am using this code and works ok, but i 'am wondering if is the correct way.
while WaitForSingleObject(MyThread.Handle, 0) = WAIT_TIMEOUT do
Application.ProcessMessages;
ShowMessage('i am done');
The VCL TThread class has its own WaitFor() method that pumps the main message queue internally when called within the main thread context:
MyThread.WaitFor;
ShowMessage('i am done');
Calling Application.ProcessMessages is generally considered a code smell. Let your main thread idle if it's got nothing to do.
If you ran a company and needed one of your workers to run to the store and grab some much-needed supplies, would you then pace by the door until he got back, or would you prefer to sit in your office and rest and wait for him, and find out that the supplies are here because you hear him walk through the door? Either way, he'll take the same amount of time, but the first way's gonna wear your legs out.
Similarly, instead of having your UI watch the thread, have the thread report back to the UI. One way to do this is to have the thread use PostMessage to send a custom message to the form that launched it once it's finished, and put a message handler on the form to respond to it.
It looks correct (if correct means it do the work). What I would change is to wait for a bit more time (50ms looks good to maintain the application responsive) while not eating CPU.
while WaitForSingleObject(MyThread.Handle, 50) = WAIT_TIMEOUT do
Application.ProcessMessages;
ShowMessage('i am done');
Sure there are other ways to do it... <joke>but I usually apply one of the main engineering principles:
if it works, don't touch it!</joke>
I agree with Mason Wheeler's remark, the main thread is best left to do its job, but I would suggest using the OnTerminate event on the thread. It is more 'Delphi natural' and the internal logic does the PostMessage bit for you. Since TThread is not a component, you can't view it in the object inspector and have to write and attach an event handler yourself. It gets called (in the main thread!) after the thread has completed/terminated.
While it looks okay, like jachguate I would use a bigger time-out value than 0 too. If you use WaitForSingleObject(MyThread.Handle, 100) then the main thread will wait a bit longer, thus eating up less CPU cycles.
A better solution would be the use of messages, though. Your application starts the thread and then puts all controls in disabled mode. The thread then executes and when it's finished, use SendMessage or PostMessage to the main window to notify it that the thread is done again. Then your application will just enable every control (and whatever else) again. This has as advantage that you keep the "natural" messageloop for the application alive, instead of running your own messageloop with this solution.Unfortunately, the message-method has one drawback: if the thread crashes then no message will be sent back, so a backup plan would be practical. For example, by adding a timer control to your mainform which checks every second if the thread is still alive. If not, it too would just activate the form again, disabling itself again.

Resources