❔ ✅ Why doesn't this basic HttpClient GET request doesn't work as expected?
I do not get anything past making a request. Neither an exception, nor an exception. I'm guessing it's because I'm not properly waiting for async to complete - but in that case what is it lacking?
Program.cs
HttpClientLib.cs
14 Replies
async void
change that to be async Task
and await it at the top level
also, don't using var client
like that, its bad practiceWhy?
Does it not log the exception? It should do that
ahh I see. I wrongly assumed
void
and Task
are both valid types, depending on your needs, but seems async code should always (for beginners atleast) be Task - is that correct?
As per your suggestion, changed using to be declerative - using HttpClient client = new();
no you shouldnt be
using
a httpclientIt should always return a Task so it can be properly awaited. There are very strict edge cases where you don't need to do that, but you probably won't encounter them. By making it a Task, you can properly await any errors.
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
read that top comment
you should NOT be creating/disposing HttpClients willy-nilly
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-8.0
yeah, always use
Task
. async void
is for fire and forget event handlers, which this is not.
unawaited async operation, so the application probably exits before the http requets is madeDunno, not enough context
sure, but thats the most likely answer for it not printing/throwing an exception
not to mention that async void swallows all exceptions anyways 😛
Thank you for the help. Reading through the docs again to understand better
👍
$close
Use the
/close
command to mark a forum thread as answeredif thats what you were going for 🙂
yeapp, will know now
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.