System.Threading TTask errors in class
## Summary When reimplementing a version of Async/Await from the blog https://www.thedelphigeek.com/2012/07/asyncawait-in-delphi.html, numerous access violations occur when running the code. ## System Information <!-- The more information are provided the easier it is to replicate the bug --> - **Operating system:** <!-- Windows, Linux (if possible, also name the distro), FreeBSD, Android, ... --> Windows 11 - **Processor architecture:** <!-- x86, x86-64, ARM, AARCH64, AVR, RISC-V, PowerPC, ... --> - X86-64 - **Compiler version:** <!-- 3.2, 3.2.2, 3.3, trunk, beta, ... (if possible, give also the git hash) --> trunk ## Steps to reproduce Class Implementation: ```uses Classes, SysUtils, System.Threading; type IAwait = interface procedure Await(const awaitProc: TProcRef); end; TAsync = class(TInterfacedObject, IAwait) private FAsyncProc: TProcRef; FAwaitProc: TProcRef; FSelf: TAsync; procedure Run; public constructor Create(const asyncProc: TProcRef); procedure Await(const awaitProc: TProcRef); end; function Async(const asyncProc: TProcRef): IAwait; implementation function Async(const asyncProc: TProcRef): IAwait; begin Result := TAsync.Create(asyncProc); end; constructor TAsync.Create(const asyncProc: TProcRef); begin inherited Create; FAsyncProc := asyncProc; end; procedure TAsync.Await(const awaitProc: TProcRef); begin FAwaitProc := awaitProc; FSelf := Self; TTask.Run(@Run); end; procedure TAsync.Run; begin FAsyncProc(); TThread.Queue(nil, procedure begin FAwaitProc(); FSelf := nil; end); end; end.``` ## Example Project Testing the class: ```Async(procedure begin ShowMessage('From Async'); end).Await(procedure begin ShowMessage('From Await'); end);``` ## What is the current bug behavior? Access violations on FAsyncProc or from within the anonymous procedure within TThread.Queue. ## What is the expected (correct) behavior? Both function references should be reached and executed. ## Possible fixes Errors are inconsistent. Sometimes putting another ShowMessage underneath the Async function code allows for FAsyncProc to be reached. Replacing TTask.Run with TThread.CreateAnonymousFunction().Start allows for the full routine to complete, only if an additional ShowMessage is added beneath the code.
issue