Assume that we have a task reference (ITask) and we want to wait (synchronously) for its completion before proceeding further.
The ITask.Wait method is provided exactly for this purpose. It also accepts an argument for the desired timeout, making it very easy to fine-tune the operation. The following code shows the ITask.Wait method:
var
LTask: ITask;
begin
LTask := TTask.Run(
procedure
begin
Sleep(5000); // Do something...
end
);
LTask.Wait();
// Completed
end;
In the previous code, assuming that we are running this code in the main/UI thread, the expected behavior here is that the task will run in the background, and the main/UI thread will synchronously wait for the task completion. Obviously, especially if the task is not immediate, this will block the main/UI thread so this is not a good practice to achieve responsiveness.
The following code shows how we can try to avoid blocking the main/UI thread for the whole execution...