In short, Parallel.Async accepts an anonymous method, normal method or procedure (all of them must be without parameters) and executes it in a background thread. That’s all.
Parallel.Async( procedure begin MessageBeep($FFFFFFFF); end,For slightly more complicated scenarios, you can also provide a second parameter, which is an anonymous method, normal method or procedure (again without any parameters) that will execute after the background task is completed. This second part of code executes in the context of the main thread so you can interact with the VCL from it.
A new demo 46_Async demonstrates this.
procedure TfrmDemoParallelAsync.btnAsyncClick(Sender: TObject); begin btnAsync.Enabled := false; Parallel.Async( procedure begin // executed in background thread Sleep(500); MessageBeep($FFFFFFFF); end, procedure begin // executed in main thread btnAsync.Enabled := true; end ); end;Clicking the button disables it and executes background task. Method btnAsyncClick then immediately exits and your app can proceed executing other code.
After half a second sleep, MessageBeep is executed in a background thread. Background task then terminates. At the end, termination code that re-enables button btnAsync is executed in the main thread.
Simple, but effective.