HttpClient hangs forever

Hello,

My project have suddenly started hanging when I run in the editor.

I have disabled all scripts except the one that fetches the data:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;

public class DataFetcher : MonoBehaviour
{
    private static HttpClient httpClient = new();
    private static Uri wineUri = new Uri("https://ipecho.net/plain");//  

    void Start()
    {
        Debug.Log("fetcher starting");
        try
        {
            string responseBody = FetchData().Result;

            Debug.Log(responseBody);
        }
        catch (HttpRequestException e)
        {
            Debug.Log("\nException Caught!");
            Debug.Log("Message :" + e.Message);
        }
    }

    static async Task<string> FetchData()
    {
        return await httpClient.GetStringAsync(wineUri);
    }

}

I do not ever see the debug log “fetcher starting”.
When I comment out the call to FetchData or replace responseBody with a string like “test”, everything proceeds and the scene loads as expected.

As soon as I involve the HttpClient, Unity hangs forever. I get no errors and have to force-quit.

Can you spot anything wrong here, or suggest how to proceed with debugging this?

Edit to add:
To make sure it isn’t something funky elsewhere in my project, I created a new 2D core project, added an empty GO and then the script above. Unity still hangs. Using 2023.3.11f1.

Can anyone confirm this behaviour, please?

You aren’t awaiting the result. Mark the Start method as async and add await before FetchData().Result.

2 Likes

Silly me.
I extracted that code from a month-old class that did a little of this and that, then suddenly stopped working even if I hadn’t changed a thing for weeks.

Your suggestions did the trick, but I’m still clueless as to why it stopped working in the first place.
meh, I guess I’ll learn to live with it. I a few years.

Thanks!

PS: I’d love to mark your reply as the answer or the thread as resolved, but I simply can’t seem to find a way to do so.

At the top of the page, click Thread Tools > Edit Title
Click the part that says “Question” and change it to “Resolved”

The compiler or IDE should actually warn you about “this call is not awaited”. Rider does that quite prominently, highlighting the statement in yellow.