Skip to content

Fix HttpClient misuse and blocking .Wait() in The-Scrolls-Of-Eldoria.cs #43

@liubchigo

Description

@liubchigo

Bug: HttpClient misuse and blocking .Wait() in Eldoria.cs

File: Solutions/CSharp/The-Scrolls-Of-Eldoria.cs

Problems

1. HttpClient instantiated inside a using block (socket exhaustion risk)

using (var httpClient = new HttpClient())
{
    string scrollContent = await httpClient.GetStringAsync(url);
    ...
}

Per Microsoft's HttpClient guidelines, creating and disposing HttpClient per request exhausts socket connections (TIME_WAIT). It should be a static readonly field or injected as a singleton.

2. .Wait() blocks synchronously on async work (deadlock risk)

public static void Run()
{
    FetchAndDecipherScroll(url).Wait();  // blocks the thread
}

.Wait() can deadlock in contexts with a synchronization context (ASP.NET, WinForms). The safer alternatives are .GetAwaiter().GetResult() or making the entire call chain async.

Fix

public class Eldoria
{
    private static readonly HttpClient httpClient = new HttpClient();

    private static async Task FetchAndDecipherScroll(string url)
    {
        // ... same logic, no `using` block around HttpClient
    }

    public static void Run()
    {
        FetchAndDecipherScroll(url).GetAwaiter().GetResult();
    }
}

Impact

This is an educational repo — modeling socket-exhausting HttpClient usage and risky .Wait() patterns teaches bad habits to learners. Both are well-known .NET pitfalls.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions