Synchronous API Connection Status Check

Synchronous API Connection Status Check

jeremyperna7254
Contributor Contributor
171 Views
0 Replies
Message 1 of 1

Synchronous API Connection Status Check

jeremyperna7254
Contributor
Contributor

Many of the functions in my .NET API plugin require connection to my ASP.NET Core WebAPI. As a result, I would like to do a connection status check before I begin to execute the bulk of the custom commands I have defined. However, the custom command methods must be synchronous, which prevents me from using the async/await keywords. I also would like to be able to cancel the execution of the API request call in some way if the request takes longer than 500ms to respond. My first attempt to solve this resulted in a deadlock when I would execute this client method call.

 

bool status = _client.ExecuteAsync<HealthCheckModel>(_baseRoute, cancelToken).Result

 

The following implementation does not cause a deadlock. However, I am concerned that I am playing with fire a bit by calling `Task.WhenAny(...).Result` since using `.Result` caused a deadlock on the client method call.

 

public bool CheckConnection()
{
    try
    {
        Task<bool> requestTask = Task.Run(async () => await _connectionStatusClient.IsConnectedAsync());
        Task timeoutTask = Task.Delay(500);

        if (Task.WhenAny(requestTask, timeoutTask).Result == requestTask)
        {
            bool status = requestTask.Result;
            Program.MainThreadContext.Post(_ => _messenger.Send(new ApiConnectionUpdateMessage(status)), null);
            return status;
        }
        else
        {
            Program.MainThreadContext.Post(_ => _messenger.Send(new ApiConnectionUpdateMessage(false)), null);
            return false;
        }
    }
    catch (Exception)
    {
        Program.MainThreadContext.Post(_ => _messenger.Send(new ApiConnectionUpdateMessage(false)), null);
        return false;
    }
}

 

Any thoughts from people about implementing an API connection status check with a timeout for my custom commands?

0 Likes
172 Views
0 Replies
Replies (0)