SignalR C#, waiting for a response from the server in TaskCompletionSource and continuing code execution

47 views Asked by At

The code is close to reality. You need to get authorization data from the client, try to log in on the server side.The server ASP.NET Core, I use SignalR. If the authorization code does not match, the server requests the code from the client again, and here the key point is that you need to go back to the part from where we requested the code, so as not to perform the authorization steps first.

This servser side:

public class AuthHub : Hub
{

    public async Task Send(string json)
    {
        try
        {
            bool isAuth = false;

            // Json has all the data and code, but it may not be suitable
            isAuth = AuthService(json);

            // Re-requesting the code
            while (!isAuth)
            {
                var tcs = new TaskCompletionSource<string>();
                await Clients.Caller.SendAsync("RequestActivationCode");
                string activationCode = await tcs.Task;

                isAuth = TryAuthAgainWithNewCode(activationCode);
            }


            if (true)
            {

            }
        }
        catch (Exception ex)
        {
          
        }       
    }

    public async Task SendActivationCode(string code)
    {
        tcs.SetResult(code);
    }

}
This client side:
hubConnection.on("RequestActivationCode",  () => {
            // Request code
            const activationCode = "32453";
        
            // Response
            hubConnection.invoke("SendActivationCode", activationCode)
                .catch(err => console.error(err));
        });

But after the client sends the code, we certainly do not return to the SendActivationCode. Of course, because string activationCode = await tcs.Task; is awaiting execution. Так тоже пробовал

Task.Run(() => tcs.Task)
0

There are 0 answers