Skip to content

LuaState.DoFileAsync not cancelling when token is set #153

@tottaka

Description

@tottaka

When CancellationToken is set, the script never actually stops running. Am I doing something wrong here?

C# code:

internal class Program
{
    static void Main(string[] args)
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        RunTest("main.lua", cts.Token);
        Task.Delay(5000).Wait();
        cts.Cancel(true);

        Console.WriteLine("Still running...?");

        // The lua code still continutes here for some reason
        Task.Delay(5000).Wait();
    }
    
    static async void RunTest(string app, CancellationToken token)
    {
        LuaState state = LuaState.Create();
        state.Environment["sleep"] = new LuaFunction("sleep", Env_Sleep);
        state.Environment["print"] = new LuaFunction("print", Env_Print);

        LuaValue[] values = await state.DoFileAsync(app, token);
        Console.WriteLine("Application exited.");
        foreach (LuaValue value in values)
        {
            Console.WriteLine(value.ToString());
        }
    }

    private static ValueTask<int> Env_Sleep(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken token)
    {
        double timeout = context.GetArgument<double>(0);
        Thread.Sleep(TimeSpan.FromSeconds(timeout));
        return new(0);
    }

    private static ValueTask<int> Env_Print(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken token)
    {
        StringBuilder sb = new();
        for (int i = 0; i < context.ArgumentCount; i++)
        {
            if (i < context.ArgumentCount - 1)
                sb.Append(context.Arguments[i].ToString() + " ");
            else
                sb.Append(context.Arguments[i].ToString());
        }

        Console.WriteLine(sb.ToString());
        return new(0);
    }
}

Lua code (main.lua):

print(1)
sleep(1.0)
print(2)
sleep(1.0)
print(3)
sleep(1.0)
print(4)
sleep(1.0)
print(5)
sleep(1.0)
print(6)
sleep(1.0)
print(7)
sleep(1.0)
print(8)
sleep(1.0)
print(9)
sleep(1.0)
print(10)

Output:

1
2
3
4
5
Still running...?
6
7
8
9
10
Application exited.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions