diff --git a/README.md b/README.md index 0702214..dc0bc66 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,51 @@ Based on code from [Cysharp's UniTask library for Unity](https://github.com/Cysh ```CSharp using Fractural.Tasks; -async GDTask DemoAsync() +public Test : Node { - await GDTask.DelayFrame(100); - - await UniTask.Delay(TimeSpan.FromSeconds(10)); - - await GDTask.Yield(); - await GDTask.NextFrame(); - - await GDTask.WaitForEndOfFrame(); - await GDTask.WaitForPhysicsProcess(); - - return "final value"; + public override _Ready() + { + // Running a task from a non-async method + Run().Forget(); + } + + public async GDTaskVoid Run() + { + await GDTask.DelayFrame(100); + + // waiting some amount of time + await GDTask.Delay(TimeSpan.FromSeconds(10)); + + // Waiting a single frame + await GDTask.Yield(); + await GDTask.NextFrame(); + await GDTask.WaitForEndOfFrame(); + + // Waiting for specific lifetime call + await GDTask.WaitForPhysicsProcess(); + + // Cancellation + var cts = new CancellationTokenSource(); + CancellableReallyLongTask(cts.Token).Forget(); + await GDTask.Delay(TimeSpan.FromSeconds(3)); + cts.Cancel(); + + // Async await with return value + string result = await RunWithResult(); + return result + " with additional text"; + } + + public async GDTask RunWithResult() + { + await GDTask.Delay(TimeSpan.FromSeconds(3)); + return "A result string"; + } + + public async GDTaskVoid ReallyLongTask(CancellationToken cancellationToken) + { + GD.Print("Starting long task."); + await GDTask.Delay(TimeSpan.FromSeconds(1000000), cancellationToken: cancellationToken); + GD.Print("Finished long task."); + } } ``` \ No newline at end of file diff --git a/tests/manual/Test.cs b/tests/manual/Test.cs index 2d47178..79b3c7f 100644 --- a/tests/manual/Test.cs +++ b/tests/manual/Test.cs @@ -1,6 +1,7 @@ using Fractural.Tasks; using Godot; using System; +using System.Threading; namespace Tests.Manual { @@ -36,6 +37,15 @@ private async GDTaskVoid Run() string result = await RunWithResult(); GD.Print($"Post got result: {result}"); + GD.Print("LongTask started"); + var cts = new CancellationTokenSource(); + + CancellableReallyLongTask(cts.Token).Forget(); + + await GDTask.Delay(TimeSpan.FromSeconds(3)); + cts.Cancel(); + GD.Print("LongTask cancelled"); + await GDTask.WaitForEndOfFrame(); GD.Print("WaitForEndOfFrame"); await GDTask.WaitForPhysicsProcess(); @@ -51,5 +61,17 @@ private async GDTask RunWithResult() await GDTask.Delay(TimeSpan.FromSeconds(2)); return "Hello"; } + + private async GDTaskVoid CancellableReallyLongTask(CancellationToken cancellationToken) + { + int seconds = 10; + GD.Print($"Starting long task ({seconds} seconds long)."); + for (int i = 0; i < seconds; i++) + { + GD.Print($"Working on long task for {i} seconds..."); + await GDTask.Delay(TimeSpan.FromSeconds(1), cancellationToken: cancellationToken); + } + GD.Print("Finished long task."); + } } }