C
Join ServerC#
help
Wait for async function in synchronous context for X time until cancel
I�Indeed 🐸1/15/2023
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
Only things I see are with usage of await but i need this method to be synchronous
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;
}
}
Only things I see are with usage of await but i need this method to be synchronous
AAngius1/15/2023
Polly's timeout might be a solution: https://github.com/App-vNext/Polly
I�Indeed 🐸1/15/2023
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;
}
}
I�Indeed 🐸1/15/2023
but it seems to be kinda ok i guess?
Since it's only a rest request (code from inside the method)
Since it's only a rest request (code from inside the method)
return JsonConvert.DeserializeObject<WeatherModel>(await RestApi.GetWebpageStringAsync(defaultInterpolatedStringHandler.ToStringAndClear()));
AAngius1/15/2023
If it just performs an API call, just call it manually with HttpClient and you'll get cancellation token support
I�Indeed 🐸1/15/2023
That makes sense. Thank you for your help ❤️