Jump to content
Vincent Parrett

VSoft.Awaitable - async/await for Delphi

Recommended Posts

https://github.com/VSoftTechnologies/VSoft.Awaitable

 

This is a simple wrapper over OmniThreadLibrary that borrows from it's Parallel.Async idea, but allows you to call functions that return values. 

 

e.g

TAsync.Configure<string>(
        function (const cancelToken : ICancellationToken) : string
        var
          i: Integer;
        begin
            result := 'Hello ' + value;
            for i := 0 to 2000 do
            begin
              Sleep(1);
              //in loops, check the token
              if cancelToken.IsCancelled then
                exit;
            end;

            //where api's can take a handle for cancellation, use the token.handle
            WaitForSingleObject(cancelToken.Handle,5000);

            //any unhandled exceptions here will result in the on exception pro being called (if configured)
            //raise Exception.Create('Error Message');
        end, token);
    )
    .OnException(
        procedure (const e : Exception)
        begin
          Label1.Caption := e.Message;
        end)
    .OnCancellation(
        procedure
        begin
            //clean up
            Label1.Caption := 'Cancelled';
        end)
    .Await(
        procedure (const value : string)
        begin
            //use result
            Label1.Caption := value;
        end);

BTW, I know this isn't really quite the same as async/await (I use C# a lot) but it's about as close as we can get right now. 

 

My use case was just to be able to make long running requests in a thread and allow the caller to cancel the requests. 

  • Like 1
  • Thanks 1

Share this post


Link to post

Is there a way to use it with "plugin" handlers instead on anonymous procedures?
There are so many pitfalls with captures.

Share this post


Link to post
1 hour ago, Lars Fosdal said:

Is there a way to use it with "plugin" handlers instead on anonymous procedures?
There are so many pitfalls with captures.

What would that look like? I guess I could try adding overloads that take regular methods, I'll have a stab at it.

 

As for captures, yes I've been caught out myself a few times. 

  • Like 1

Share this post


Link to post

@Lars Fosdal I tested with regular methods and it does work fine. 

 

I updated it today to include overloads for procedures (ie where you don't need to return anything). 

  • Like 2

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×