THostedWorker Class
Base class for something with a loop of its own -- a job runner, a poller, a scheduler.
Remarks
Override Execute and nothing else. The host gives it a thread on Start and signals the token on Stop, then waits for the thread to finish.
Pass the token down into whatever the loop calls, so that a long unit of work can give up in the middle instead of holding up the shutdown. When the loop blocks on something other than the token - a queue, a socket, an event of its own - register a callback on the token that wakes that wait up.
An exception escaping Execute brings the whole host down rather than leaving a process that is up and doing nothing. The one exception is EOperationCancelled raised after the stop was requested: that is how a unit of work gives up when asked to, and it ends the worker cleanly. Catch exceptions inside the loop for failures that must not stop the server, such as one run of a job that failed.
A worker does not need a host. Outside one, call Start and Stop directly and free it like any other object - or hold it in an interface reference, but do not mix both. Freeing a worker that is still running stops it first.
Syntax
Unit: Sparkle.Host.Contracts
THostedWorker = class(TInterfacedObject, IHostedService);
Constructors
| Name | Description |
|---|---|
| Create | Virtual so that the host can build it from a class reference. |
Methods
| Name | Description |
|---|---|
| BeforeDestruction | Stops a worker that is still running, before any destructor runs. |
| Start | Starts Execute on a thread of its own and returns at once.Raises if the worker is already running. |
| Stop | Signals the stop token and waits for Execute to return. Does nothing if the worker is not running. |