Avatar ·

How to synchronously execute an async Task<T> method in C#?

Hello everyone! I'm writing a console application in C# (.NET Framework 4.7.2) and encountered a problem. I have an async method that returns Task: ```csharp public async Task GetDataAsync() { using (var client = new HttpClient()) { var result = await client.GetStringAsync("https://api.example.com/data"); return result; } } ``` The problem is that I'm calling this method from a synchronous context, for example, from a class constructor or from the Main method (which is not async). I cannot make the calling method async because it would break the architecture (for example, a constructor cannot be async). I've tried different approaches: - `GetDataAsync().Result` — the program hangs (deadlock). - `GetDataAsync().GetAwaiter().GetResult`