Search code examples
c#asp.net-coreasync-awaitsignalrintegration-testing

Wait hub to execute on method to proceed C#


I'm making an integration test and want a method to wait until "on method" is called. In C#.
Something like this:

public async Task CheckMethod(){
    var hubConnection = GetHubConnection();
    connection.On("OnMethod",async () =>{
        Log("First");
    }
    await connection.InvokeAsync("Subscribe", id);
    // Something to wait then proceed
    Log("Second");
}

Solution

  • Try this:

    public async Task CheckMethod()
    {
        var tcs = new TaskCompletionSource<object>();
        var hubConnection = GetHubConnection();
        connection.On("OnMethod",() =>
        {
            Log("First");
            tcs.TrySetResult(null); 
        }
        await connection.InvokeAsync("Subscribe", id);
        Log("Second");
        await tcs.Task;
        Log("Third");
    }