doghappy / socket.io-client-csharp

socket.io-client implemention for .NET
MIT License
721 stars 124 forks source link

EmitAsync not being cancelled with CancellationToken #285

Open xultz opened 2 years ago

xultz commented 2 years ago

I made a simple websocket server with Flask-SocketIO running on gevent-websocket. I can connect to it, send and receive messages as expected. I'm trying to cancel an EmitAsync with a cancellation token, but it looks like it is not cancelling.

In the server, I created an endpoint that runs this code:

@socketio.on("mensagem")
def on_mensagem(dados):
    print(f"Received: {dados}")
    time.sleep(2)
    return "Here is the response"

As you can see, this endpoint receives the message from a client, waits for 2 seconds, and then sends a response. I made a function triggered by a button in a Winforms application with this code:

private async void pbTest_Click(object sender, EventArgs e)
{
    CancellationTokenSource cts = new CancellationTokenSource();

    Console.WriteLine("{0} Sending the message", DateTime.Now.TimeOfDay);

    await socketio.EmitAsync("mensagem", 
        cts.Token, 
        response => Console.WriteLine("{0} Response: {1}", DateTime.Now.TimeOfDay, response.GetValue<string>(0)), 
        "testing");

    Console.WriteLine("{0} Cancelling the token", DateTime.Now.TimeOfDay);
    cts.Cancel();
    Console.WriteLine("{0} Cancelled", DateTime.Now.TimeOfDay);
}

The code sends the message to the server endpoint, and right after that, it cancels the token and returns. On the console, I see the folling messages:

23:04:24.5157933 Sending the message
23:04:24.6293946 Cancelling the token
23:04:24.6300886 Cancelled
23:04:26.6434338 Response: Here is the response

As you see, it sends the message, cancels the token and returns from the function, but after the two seconds the Action function is executed, looking like the CancellationToken is being ignored.

envoydev commented 1 year ago

Same for me