C
C#2y ago
Indeed

Wait for async function in synchronous context for X time until cancel

Hi! How can i wait X time for this function to finish or otherwise throw/cancel/return something This function comes from an outside library
public bool ValidateAddress(Address address) {
try {
//wait for x or throw
weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
return true;
}
catch {
return false;
}
}
public bool ValidateAddress(Address address) {
try {
//wait for x or throw
weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
return true;
}
catch {
return false;
}
}
Only things I see are with usage of await but i need this method to be synchronous
4 Replies
Angius
Angius2y ago
Polly's timeout might be a solution: https://github.com/App-vNext/Polly
Indeed
Indeed2y ago
I think I've figured it out without a library, the only problem I've encountered is lack of ability to lack my task since the library doesnt expose parameter for cancellation token
public bool ValidateAddress(Address address) {
return TryValidateAddress(address).Result;
}

private async Task<bool> TryValidateAddress(Address address) {
var task = weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
if (await Task.WhenAny(task, Task.Delay(1000)) == task) {
return true;
}
else {
return false;
}
}
public bool ValidateAddress(Address address) {
return TryValidateAddress(address).Result;
}

private async Task<bool> TryValidateAddress(Address address) {
var task = weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
if (await Task.WhenAny(task, Task.Delay(1000)) == task) {
return true;
}
else {
return false;
}
}
but it seems to be kinda ok i guess? Since it's only a rest request (code from inside the method)
return JsonConvert.DeserializeObject<WeatherModel>(await RestApi.GetWebpageStringAsync(defaultInterpolatedStringHandler.ToStringAndClear()));
return JsonConvert.DeserializeObject<WeatherModel>(await RestApi.GetWebpageStringAsync(defaultInterpolatedStringHandler.ToStringAndClear()));
Angius
Angius2y ago
If it just performs an API call, just call it manually with HttpClient and you'll get cancellation token support
Indeed
Indeed2y ago
That makes sense. Thank you for your help ❤️