Summary

While this chapter focused on a single topic, it was still quite diverse. You've learned everything about the TThread class, which is a basis for all multithreading code in Delphi. Even the task-based approach that we'll explore in the next chapter uses TThread as a basic building block.

I have shown three different ways of creating a TThread-based, multithreading solution. A program can take complete ownership of a thread so that it is created and destroyed by the owner. This approach is best used when a thread implements a service, as in such cases the main program knows best when the service is needed.

Another way, more appropriate for background calculations, is FreeOnTerminate mode. With this approach, a thread object is immediately destroyed when a thread's Execute function exits. The thread owner can set up an OnTerminate event to catch this condition and process the result of the calculation.

Instead of writing a separate class for each background operation, we can also create a thread that executes an anonymous method. This approach is most appropriate for short-lived tasks that don't require any interaction with the thread's owner.

After that, we looked into exception handling inside a thread. I've also discussed a few other important TThread methods and properties.

The second half of the chapter focused on writing better threading tools. Firstly, I have extended a TThread with two communication channels. The result, TCommThread, can be used as a base class for your own threads, which can use these channels to communicate with the thread owner.

For the finishing touch, I have implemented a specific solution for one usage pattern—a background task that can send and receive messages and react to timer events. I have then shown how you can produce very clean and understandable code, by using such threading implementation.

In the next chapter, we'll focus even more on a usage-pattern approach. We'll dig deeply into Delphi's Parallel Programming Library  (PPL), which is all about usage patterns. For good measure, I'll also implement a few patterns that PPL doesn't cover.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.179.58