The Web vNext

I have been reading a lot about Web development lately, and pondering the future of web development.  For the longest time I shied away from Web development, largely because it was so laborious and frustrating. I dabbled a bit back when people were using COM objects with VBScript on the server and Javascript on the client in classic ASP pages. Even back then, companies were making software look like Windows applications within the browser (IE).  By today’s standards, those applications look dated, but today’s web SPAs function in a similar manner, although great progress has been made in standardizing browsers, abstracting out their idiosyncrasies using frameworks, and handling variable display sizes.  My current experience is that it’s still harder and more time consuming to develop a good web application, and they are still not as rich as a Windows app IMHO. That begs the question as to why people are writing applications for the web anyway.  For eCommerce sites, I get it, but for other line of business applications why not throw off the shackles of HTML/CSS and embrace a new UI framework altogether?  Now I know what you’re thinking…..this guy has lost it and wants to re-invent the web which a lot of smart people have worked on for years to make Web 2.0 a reality.  Before you call the white coats, read on… When a user goes to a web site for any commercial activity they should be ensuring the website has a valid SSL certificate from a trusted authority.  The Internet is a dangerous place these days where web sites may be trying to attack your computer.  We download content from such sites into our sand boxed browser. This is not that much different than downloading a signed application.  We use signed applications all the time now, when using applications on our phones, tablets and desktops from the “app stores”.  The only difference is whether the store owner i.e.: Apple, has reviewed the application testing for malware.  Open source software such as Tortoise Git is often signed as well to ensure users trust that the application they are getting is from the advertised source and is safe to use.  I think it’s safe to say that most people would trust a signed application. With that premise in hand, why aren’t we all writing signed Desktop apps using REST back ends?  Or if we really want to leverage single source cross platform applications, why not use WASM with a UI framework that allows an application to be written in languages that are typically used for native desktop, and mobile devices such as C#, Delphi, or C++? The performance of even Javascript is pretty decent.  Many games have been ported to the browser using Javascript transpilers or EmScripten.  WASM allows developers to take this one step closer to the metal (CPU) and skip the run-time parsing and execution of Javascript.  Blazor is a project that does just that, within the confines of HTML/CSS, but also shows the possibility of using WASM with a different presentation framework such as Uno, or Ooui.  Obviously I’m not the only one thinking that a different presentation layer might be overdue in the web space. One of the advantages of Blazor is to eliminate some of the third party dependencies, making the development stack more reliable, and to use the same technology and tools throughout.  Of course you can learn and use Javascript throughout the entire stack now, or a Javascript transpiler, but without WASM using your development language of choice is not possible. I would like to see Object Pascal support the entire development stack.  Preferably the same language dialect and core libraries.  Perhaps something similar to Blazor, or maybe FMX targeting the web with WebGL.  All we need is to be able to capture the compiler IR and feed it into the WASM LLVM back end (okay there might be a little more to it than that).  The web is a huge horizontal market that is ripe for disruption and with the right moves, Delphi could grab a chunk of that segment, making the product relevant again. What do you think is the future of Javascript on the web?  Will it be dethroned at some point by WASM? Is the future of the Web HTML/CSS, a different UI layer, or perhaps a mix depending on the type of web app?  Should I dust off the Delphi .NET compiler to generate MSIL to feed the Mono WASM run-time, or do we need a way to get the current compilers to output LLVM IR? Maybe it’s just time to call the white coats as pondering all the options can drive you crazy…
Read More

TMS WEB Core: a bridge to the future!

Intro

While working in the TMS Labs this week, we had a fruitful discussion on how we could interact with a desktop or mobile environment, where the browser that hosts a TMS WEB Core application, runs on. We already had some experience creating a JavaScript bridge between a TWebBrowser and Google Maps (http://www.tmssoftware.com/site/webgmaps.asp) and figured out this could be useful for TMS WEB Core as well. We wanted to give the user the capability of hosting its TMS WEB Core application in a native desktop or mobile application that offers access to all of the operating system functionality and make it accessible via the browser.

Finding an entry point

We created a TTMSFNCWebCoreClientBrowser class that acts as the communication and viewing component for a TMS WEB Core application. To setup the communication, we needed an entry point. In JavaScript, a global variable can be defined and that was just the entry point we were looking for. In TMS WEB Core, during the creation of TApplication, we also injected a global variable “TMSWEBCoreClientBrowser”, that is initialized with a string “unknown”. This variable is filled in, when the TTMSFNCWebCoreClientBrowser establishes a conection to the TMS WEB Core application.

  if ExecuteJavascript('document.readyState', true) = 'complete' then
  begin
    if ExecuteJavascript('window.TMSWEBCoreClientIdentifier', true) = 'unknown' then
      FInitialized := True;
  end;

Handshake

After the initialization is complete, the TTMSFNCWebCoreClientBrowser instance performs a handshake. This is being done by executing JavaScript. The HandshakeScript is dynamically being added during the initialization of the TMS WEB Core Application and initializes the TMSWEBCoreClientIdentifier global variable.

initialization
begin
  HandShakeScript := TJSHTMLScriptElement(document.createElement('script'));
  HandShakeScript.id := 'HandShakeScript';
  HandShakeScript.type_ := 'text/javascript';
  HandShakeScript.innerHTML :=
  'var TMSWEBCoreClientIdentifier = "unknown";'+#13#10+
  'function HandShake(cid){'+#13#10+
  '  TMSWEBCoreClientIdentifier = cid;'+#13#10+
  '}';
  document.body.appendChild(HandShakeScript);

  Application := TApplication.Create(nil);
end;

The handshake script is being called from the TTMSFNCWebCoreClientBrowser instance after the initialization is complete.

procedure TTMSFNCCustomWebCoreClientBrowser.PerformHandshake;
var
  c: string;
begin
  {$IFDEF MSWINDOWS}
  c := 'windows';
  {$ENDIF}
  {$IFDEF MACOS}
  {$IFDEF IOS}
  c := 'ios';
  {$ENDIF}
  {$IFNDEF IOS}
  c := 'macos';
  {$ENDIF}
  {$ENDIF}
  {$IFDEF ANDROID}
  c := 'android';
  {$ENDIF}
  ExecuteJavascript('HandShake("'+c+'");');
end;

Sending and receiving messages

When the handshake is complete, the client can send and receive messages. The communication format is a JSON string that is automatically URL encoded and parsed to a JSON object. A sample sending from the client to the TMS WEB Core application:

procedure TForm1.ClientSendButtonClick(Sender: TObject);
var
  c: TJSONObject;
begin
  c := TJSONObject.Create;
  c.AddPair('Message From Client', 'Hello World !');
  w.Send(c);
  c.Free;
end;

And of course, sending back from a TMS WEB Core Application to the client:

procedure TForm1.WebButton1Click(Sender: TObject);
var
  o: TJSONObject;
  js: TJSON;
  s: string;
begin
  js := TJSON.Create;
  s := '{"Message From TMS WEB Core Application":"'Hello World !"}';
  o := js.parse(s);
  w.Send(o);
  o.Free;
end;

The future

This technology opens up a lot of possibilities for the future. You can send and receive messages with plain text, as well as small binary data encoded inside a JSON string between the client and the TMS WEB Core Application. The client application can then interact with the operating system, such as opening files, and other operating system specific functionality. The code runs on FMX (Windows, macOS, iOS, Android) and VCL (Windows) and is coming to TMS WEB Core in the near future!

Read More

Read More

Better Performance with REST Compression

Many Delphi applications, esp. mobile iOS or Android apps, are using REST, to retrieve data from a backend. Often TRESTClient and TRESTRequest are used to get access to an external REST api. There several Blogs and CodeRage videos (including from me), that demonstrate how to do this. Even the Delphi… Read More Der Beitrag Better Performance with REST Compression erschien zuerst auf Developer Experts.
Read More

Visiting the TMS lab day 7: TMS WEB Core testing and exploring

With the ever growing number of TMS WEB Core UI controls we have and the ever growing complexity, testing web UI controls becomes a non-trivial task. Our team clearly has a need to allow an efficient way testing not only by the developer of the UI controls but also by other users. One of the chores for testing a UI control with numerous settings that affect the appearance and the behavior, is that typically an application needs to be developed that will surface all the combinations of settings. And then we are not yet talking about interactions between multiple UI controls. So, we found ourselves both writing a lot of test application code and also going a lot through the cycle of configuring a UI control, compile, run, test and repeat with other configurations.

Out of this laborious experience, the idea for creating a test environment was born. We wanted to have a runtime test environment for the TMS WEB Core components. Wanting the ability to test with every possible property setting of the control and realizing we had in our TMS FNC UI Pack component library an object inspector control, developing this test environment turned out to be faster than we imagined.

After using our test environment for a while now, we realized that this would probably also be interesting for users new to the TMS WEB Core framework. It allows to play with the TMS WEB Core UI Controls directly from the web without the need to install anything. It allows to learn all features and capabilities and discover the rich set of controls meanwhile available that can help you build your web applications. So, we thought of a name for this environment and came up with “Component Explorer”.

During these 2 weeks of visits to the TMS lab, we wanted to show you the experimental version of our Component Explorer. You can use it to explore our TMS WEB Core UI controls, play with it without installing it, experiment and test. And oh, of course we would appreciate if you’d let us know if you find an issue so our team can look into it.

Head to http://www.tmssoftware.biz/tmsweb/demos/ComponentExplorer now and discover.

Some notes for your information:

  1. A nice technical detail about the Component Explorer is that it is not a monolithic single-page web application. This means that the Component Explorer consisting of the Object Inspector, designer and component palette dynamically loads the UI control libraries. So, when we develop new UI controls or update the UI controls, this can be done by deploying compiled UI control library JavaScript files to a “component” folder.
  2. Another nice tidbit, is that the Component Explorer is mainly made up of FNC UI controls. The Object Inspector, the design surface, the tool palette, … were all developed with TMS FNC UI Controls. Given that FNC controls can be used for VCL, FMX, LCL and WEB, this means that theoretically, we could also create a desktop Component Explorer versions. In that case it would be limited to exploring FNC controls of course as the native TMS WEB Core UI controls of course cannot be used from VCL, FMX or LCL applications
  3. There is an edit mode and runtime mode. Normally on the design surface, the mouse interacts with the UI controls to move & resize the controls. When unchecking the “Edit Mode” checkbox, we can interact with the UI controls directly with the mouse.
  4. There are still several shortcomings in the Component Explorer. One of these shortcomings is that it is not yet possible to insert controls as child of other controls. All inserted controls are child of the form. So far, for our testing purposes, we could live with this limitation but as our testing becomes more complex (for example testing a ribbon control), this is something high on the priority list.
  5. Although there is already a TStringList property editor, TCollection property editor, there is no mechanism yet for custom property editors. Class properties can be edited by expanding the class and that is in most of our testing scenarios more than sufficient.
  6. In working on integrating testability of our TMS XData backend framework, we discovered a nice side effect that we could create on-the-fly not only a component exploring environment but also a data exploring environment. An example for exploring this, is by dropping a TXDataWebDataSet, TXDataWebConnection, TWebDataSource and TWebDBGrid on the form. Hook the grid to the datasource, the datasource to the dataset and the dataset to the connection. You can use your own XData endpoint or you can use our test endpoint https://app.devgems.com/music Then set the TXDataWebConnection.Active to true and set TXDataWebDataSet.DesignLoad to true. You can see now the XData data in the TWebDBGrid.

  7. We did use Bootstrap in the Component Explorer, so you can also play with Bootstrap styles. Use the TMS WEB Core UI controls ElementClassName property to assign a fitting Bootstrap class and it should update live. For example, drop a TWebButton on the form and set WebButton.ElementClassName = ‘btn btn-primary’ and you should get a nice looking blue Bootstrap button.

Lab visit feedback & win!

Our team loves to hear what you think about what is brewing in the lab, how you plan to use the upcoming features, what priority our team should give to it and if you have possibly interesting and/or creative ideas to make this even more powerful for Delphi developers. To reward your interaction & feedback, we’ll pick 3 blog comments on October 15 that we liked the most and first prize is a free TMS WEB Core license, the 2nd and 3rd prize is a 50% discount coupon on TMS WEB Core. Let yourself hear to increase your chances!

Get started

Meanwhile, you can go ahead and explore the new & exciting territories of web client development that become available for Delphi developers with TMS WEB Core! You can download the trial version that is generally available, go ahead with the standalone version you purchased or with TMS WEB Core and additional tools that are all included in TMS ALL-ACCESS. Or you can come to see TMS WEB Core and discover and discuss it face to face with Bruno Fierens of tmssoftware.com showing it in London on October 23, 2018. Note also that in October, you can still take advantage of purchasing TMS WEB Core at launch price from 295EUR for a single developer license. From Nov 1, regular pricing will be active on TMS WEB Core (395EUR for a single developer license).

Read More

Read More

Visiting the TMS lab day 6: TMS WEB Core Progressive Web Apps

Another day, another visit this week in the TMS lab and today we’re going to have a look at what progressive web application development can bring for us, Delphi developers and how we prepare TMS WEB Core in the lab to be ready to take advantage of this technology.

First of all, what exactly is a “progressive web application”?

Easiest is to borrow the information from Wikipedia on progressive web applications:


Progressive Web Apps (PWAs) are web applications that load like regular web pages or websites but can offer the user functionality such as working offline, push notifications, and device hardware access traditionally available only to native mobile applications. PWAs are an emerging technology that combine the open standards of the web offered by modern browsers to provide benefits of a rich mobile experience.

What does it mean in relationship to TMS WEB Core?

This means a couple of things for the application:

  • Adapts automatically to the device screen, i.e. looks good on mobile and desktop. Also called responsive design
  • Is aware of online versus offline state, i.e. continues to work in offline state
  • Can be installed on a mobile device, Chrome OS machines and most likely in the future also on desktop machines without going to a censored application store
  • Will look like a native application, i.e. will use the full screen on the mobile device, no navigation bar etc..
  • Has access to device hardware
  • Will need to be initially accessed via HTTPS

As such, we are working in the lab to make it as easy as possible to create PWAs directly from TMS WEB Core with minimal effort. As a proof of concept, we created with TMS WEB Core and some manual help (that will become automated in the future) a full 100% compliant progressive web application.

First a word about compliance testing. A great tool for web application developer is Google Lighthouse. With Lighthouse, you can directly submit your web application to several tests related to performance, accessibility, best practices, SEO and compatibility with progressive web app requirements.
This proof of concept is a simple calculator. It is built using:

  • The TTMSFNCWidgetLCDLabel as display that is top aligned
  • The TWebGridPanel as automatic sizing grid that is client aligned
  • The TWebGridPanel is configured with 4 25% width columns and 5 20% height rows
  • The TWebButton controls on the TWebGridPanel are client aligned on the panel

Responsive design
This layout already takes care of properly adapting to mobile, tablet and desktop screens, so makes it responsive if you want to call it this way

Service worker
Next we need to make this application work offline. This is achieved through a service worker. A service worker is JavaScript code that instructs the browser how to deal with fetching the parts that make up the application. So, we manually created the serviceworker.js file that gets registered from the main HTML file. This service worker contains the code to instruct the browser to install all involved files in the cache.

Manifest file
To make the application installable on a mobile device, there needs to be a manifest.json file that holds details about the application, including the application icon that will appear on the mobile device to start the application from. So, we’ve created such manifest.json file here as well as icon files (PNG format) in several sizes with our company logo as application icon.

With all this in-place, it is time to start verifying we effectively have a progressive web application. With Google Lighthouse installed in the Chrome browser, this is as easy as navigating to our web application and starting Lighthouse to let it generate a report.
So, in this case, we have deployed the prototype application to:

https://www.tmssoftware.com/pwa/calculator.html

and when we let Lighthouse generate its report, we get the result:

All in all, a pretty impressive result overall (certainly when you compare to many mainstream websites) and 100% satisfying the progressive web application requirement. While the performance is mostly server related here, this is not something directly under control of the TMS WEB Core application, but our team is committed to make TMS WEB Core applications shine even more in the other areas.

Now that we have the confidence that we really have a progressive web application, we can do the next step and try it out on a mobile device, in this case an iPhone. While Android had support for PWAs for some time already, since iOS 11.3, Apple also added support too.

So, when we navigate to the application URL https://www.tmssoftware.com/pwa/calculator.html, we can now choose to add it to the desktop:

From the manifest, iOS found out the application name & icon and suggests to add it this way to the desktop:

And now comes the really nice thing, let’s switch the iPhone to airplane mode (notice the airplane mode indicator in the top left corner of the screen), we can still start our TMS WEB Core application and use it:

Conclusion

Progressive web applications will play in many ways a very important role and will be a crucial technology to make web applications behave nicely when switching between online / offline situations, switching between desktop and mobile devices and as such offer a better user experience. Moreover, it offers a mechanism to deploy applications to end-users without passing via the Apple, Google or Microsoft gateways and paywalls. We’re researching and implementing the needed support in the TMS WEB Core framework to make developing such progressive web applications as easy as it can be.

Thanks

A big thank you goes to Danny Wind , a long time Delphi guru, trainer, Embarcadero MVP, … who brought up the initial ideas and experimental work to create progressive web applications from TMS WEB Core apps!

Lab visit feedback & win!

Our team loves to hear what you think about what is brewing in the lab, how you plan to use the upcoming features, what priority our team should give to it and if you have possibly interesting and/or creative ideas to make this even more powerful for Delphi developers. To reward your interaction & feedback, we’ll pick 3 blog comments on October 15 that we liked the most and first prize is a free TMS WEB Core license, the 2nd and 3rd prize is a 50% discount coupon on TMS WEB Core. Let yourself hear to increase your chances!

Get started

Meanwhile, you can go ahead and explore the new & exciting territories of web client development that become available for Delphi developers with TMS WEB Core! You can download the trial version that is generally available, go ahead with the standalone version you purchased or with TMS WEB Core and additional tools that are all included in TMS ALL-ACCESS. Or you can come to see TMS WEB Core and discover and discuss it face to face with Bruno Fierens of tmssoftware.com showing it in London on October 23, 2018. Note also that in October, you can still take advantage of purchasing TMS WEB Core at launch price from 295EUR for a single developer license. From Nov 1, regular pricing will be active on TMS WEB Core (395EUR for a single developer license).

Read More

Read More

Calling Application.ProcessMessages in a Delphi program

Using Application.ProcessMessages is being frowned upon by many because often it means that your program design is flawed. These people usually suggest you should use multi-threading instead, which then opens another can of worms. First of all, let me make clear, that I am talking about Windows programs written in Delphi using the Visual Component Library (VCL). This is not about Android or IOS development and also not about the Firemonkey (FMX) framework and most certainly not about any dotNET language. With that out of the way, let’s discuss what Application.ProcessMessages does and why it is being used: Application is the global object declared by the VCL in the Forms unit which provides methods that are independent of forms. One of them is ProcessMessages. What it does is looking into the Windows message queue and processing any messages it may find there. Since Windows GUIs are message driven, this is important for a program to react to user input as well as other events, e.g. redrawing controls that have changed. Normally this processing of messages is done automatically in the program’s main message loop that is executed all the time when it is idle. But if your program does some long running work after e.g. the user pressed a button, it might take a while until it gets back to executing the message loop and to the user it will seem to have crashed or hung. To alleviate this, for many years Delphi programmers have added the occasional call to Application.ProcessMessages in their code. This usually looks like this: proccedure TMyForm.b_Exectue(Sender: TObject); var i: integer; begin for i := 0 to GetCount - 1 do begin DoSomeWork(i); Application.ProcessMessages; end; end; Where DoSomeWork does part of the total work and returns. And then the program calls Application.ProcessMessages to update the user interface. Why is this bad? Processing Windows messages may have some undesired side effects. E.g.: Your form might have multiple buttons which do different things. ButtonA might start a long running calculation A while ButtonB might start a different calculation B. And it’s most likely that you don’t want to start calculation B while calculation A is still running. Your calculation might access the user interface to retrieve some configuration. If you do that frequently and in between call Application.ProcessMessages, these settings may have changed, so you might start with one set of configurations and continue with a different one. The result will most likely not be what you expect. The user might close the form while the calculation is still running. That could result in resources that the calculation needs being freed, which usually causes errors like Access Violations. Each call to Application.ProcessMessages takes time which might slow down your calculations significantly. So, should we not call Application.ProcessMessages? And how do we keep the GUI active? As mentioned above, the answer you usually get is to use multi-threading. That is: Move the work into a secondary (or even many secondary) worker thread and let the main thread take care of the user interface. If done properly this works very well. But can you do it properly? Well, I for one have written my share of multi-threaded programs and I can tell you: It’s difficult to do it properly. And most of the time it isn’t necessary. One of the main stumble blocks is debugging. The Delphi debugger is not particularly suited for debugging multi-threaded programs. It shows you a list of threads and the code which is being executed by the currently active thread (on a multi core system, there is more than one currently active thread, I have no idea how the debugger selects the one to display). You can switch to a different thread and look at the code it is executing. Even worse: The debugger will switch between the threads automatically for no apparent reason, so you press F8 to step over one command and find yourself in the code of a different thread all of a sudden. Other than the debugger, there are of course other debugging methods, e.g. writing to a log or showing message boxes. The latter can only be done safely in the main thread because the VCL is not thread safe. Writing a log will pose the challenge of accessing that log in a thread safe manner. All that does not mean, you should not use multi-threading if you need it. It just means that you should consider the implications this will have on the complexity of your code and debugging it. This blog post is not about multi-threading in particular but about Application.ProcessMessages, so I will not go down that route any further. So, what can we do with a single threaded program to alleviate the above mentioned pitfalls of Application.ProcessMessages? First of all: Once you start processing some data, stop the user from interfering. Disable the controls in the user interface, including the button that just started the processing. This also gives the user feedback that the program is busy right now. He cannot start anything else and also not change the settings being used by the calculations. Don’t forget to enabled the controls afterwards (e.g. use Try…Finally to ensure them to be re-enabled.) Prevent the current form from being closed. This can be done with an OnCloseQuery event. Call Application.ProcessMessages as often as necessary, but not too often. In addition you should provide a visual feedback of the progress and have an Abort button that allows the user to – well – abort the calculations. Basically you do something like this: procedure TMyForm.SetIsRunning(_Value: boolean); begin // set a flag that can be checked elsewhere FIsRunning := _Value; // en-/disable the button that started this b_Execute.Enabled := not _Value; // en-/disable any configuration controls fe_InputFile.Enabled := not _Value; fe_OutputFile.Enabled := not _Value; chk_SomeSetting.Enabled := not _Value; // en-/disable the Abort button, note the missing "not" here! b_Abort.Enabled := _Value; // ensure that the Abort button has the correct caption b_Abort.Caption := _('Abort ...'); // reset a flag that tells you to abort FAborting := False; end; procedure TMyForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Result := not FIsRunning; // you might want to add a message box here to ask the user if he // wants to abort end; procedure TMyForm.b_AbortClick(Sender: TObject); begin // you might want to add a message box here to ask the user if he // really wants to abort // set the flag that the user wants to abort processing FAborting := True; // give him feedback that we are doing what he requested b_Abort.Caption := _('Aborting ...'); end; procedure TMyForm.b_ExecuteClick(Sender: TObject); var LastAPMCall: Int64; ThisAPMCall: Int64; i: integer; begin SetIsRunning(True); try LastAPMCall := GetTickCount; for i := 0 to GetCount - 1 do begin DoSomeWork(i); // now, instead of calling Application.ProcessMessages every time // we check that the last call was more than 100 ms ago ThisAPMCall := GetTickCount; if (ThisAPMCall - LastAPMCall > 100) or (ThisAPMCall < LastAPMCall) then begin // GetTickCount is a 32 bit value that wraps around about // every two weeks. That's what the second check is for. Application.ProcessMessages; LastAPMCall := ThisAPMCall; if FAborting then begin // The user has pressed the Abort button, so we do what he wants SysUtils.Abort; end; end; end; finally SetIsRunning(False); end; end; That’s the basic principle which many of our internal tools use. It avoids the complexity of multi-threading while still keeping the UI responsive and allow the user to abort processing. I’m not claiming that it is perfect but it works, is simple to understand and also simple to debug. Drawbacks are the following: If the processing is more complex and should be moved to a procedure in a different unit, it’s easy to forget the Application.ProcessMessages calls. Also if you have these calls in your code, you should not call it in a secondary thread. Bad things will happen, if you do. If you call Application.ProcessMessaging in multiple places, it might not be as easy as in the example to keep track of how long ago the last call was. One possible solution is to have a global TTimedProcessMessages object that does the time keeping for you. Checking the Abort button is also a problem once your code is no longer in the form’s object. Again, a TTimedProcessMessages object can solve that. You cannot use that code in Firemonkey programs and, most unfortunately, you cannot use it for cross platform programs (which would require Firemonkey anyway.) Nowadys most computers have multiple cores. This is a single threaded program, so it will only use the processing power of one core. Depending on the amount of processing that needs to be done and whether it can be split into independent work packages, a multi-threading solution would be much more efficient. Oh, you might ask, where this TTimedProcessMessages object I am talking about can be found. Here you go: type PBoolean = ^Boolean; TTimedProcessMessages = class private FDummyBool: Boolean; FAbortedFlag: PBoolean; FLastCall: Int64; FMinTicks: Int64; public constructor Create(_MinTicks: integer; _AbortedFlag: PBoolean = nil); function Execute(var _WasAborted: boolean): boolean; overload; function Execute: boolean; overload; end; constructor TTimedProcessMessages.Create(_MinTicks: integer; _AbortedFlag: PBoolean = nil); begin inherited Create; FMinTicks := _MinTicks; if Assigned(_AbortedFlag) then FAbortedFlag := _AbortedFlag else FAbortedFlag := @FDummyBool; end; function TTimedProcessMessages.Execute(var _WasAborted: boolean): boolean; var ThisCall: Int64; begin ThisCall := GetTickCount; Result := (ThisCall - FLastCall > FMinTicks) or (ThisCall < FLastCall); if Result then begin Application.ProcessMessages; _WasAborted := FAbortedFlag; end else _WasAborted := False; end; function TTimedProcessMessages.Execute: boolean; var DummyBool: Boolean; begin Result := Execute(DummyBool); end; You either create a global variable (no, of course that’s bad) a singleton of this class gblTimedProcessMessages := TTimedProcessMessages.Create(100, @FAborting); or create an instance and pass it around to all methods that need it. These methods then use it like this: if gblTimedProcessMessages.Execute(WasAborted) and WasAborted then SysUtils.Abort; (Note: All the code above has just been typed in as I went along, so it might contain bugs. I haven’t even tried to compile it.) There you go. Good thing I have disabled comments on this blog anyway, so there will be no way for people to call me unprofessional because I recommend using Application.ProcessMessages. 😉 But if you really want to call me names, here is the corresponding Google+ post.
Read More