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

  • Operating system: Windows 11
  • Processor architecture:
  • X86-64
  • Compiler version: trunk

Steps to reproduce

Class Implementation:

  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.
Edited by sollapse