Reputation: 2851
I have the following lines of code which check if a device is registered in a database using an async method.
if (CrossConnectivity.Current.IsConnected)
{
return await App._deviceService.GetDevice(id);
}
I had assumed that the await would have done just that - waited on GetDevice completing then return it's value, but on looking into I think that I need to use a callback if I want to get the actual result of the call so I can act upon it.
Can anyone tell me if I'm going down the correct route with this? Below is the called async task
public async Task<bool> GetDevice(string deviceID)
{
string url = Resources.Urls.dev + Resources.DeviceApi.Get + "?id=" + deviceID;
HttpResponseMessage result;
result = await App.HttpClientInstance().GetAsync(url);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return true;
}
return false;
}
Upvotes: 1
Views: 3463
Reputation: 39072
No, actually using await
on call of method defined like this (Task<bool>
) means the caller will "wait" for the return value to be ready, so your return
will either return true
or false
based on the result of GetDevice
call.
Update: I am clarifying that the code does not actually actively wait for the method to complete, because that would defeat the purpose of the async/await
combo, but I meant that the return
statement will execute only after the method actually completes. While the HttpClient
request runs, the calling thread is free to do other tasks in the meantime, which is the true advantage of using async/await
.
Upvotes: 4
Reputation: 32068
return await App._deviceService.GetDevice(id);
This will return whatever GetDevice
returns (true
or false
). You don't need to do anything further as you are already await
ing for the Task
to complete.
A minor suggestion would be to change your GetDevice
return to
return result.IsSuccessStatusCode;
So that you don't depend directly on 200
but rather 2xx
(any success code).
Upvotes: 1