-1

Trying to do a get request but it keeps giving me "null" as a response, tested the URL and there seems to be no problem with it.

using System.Net.Http;
using System.Threading.Tasks;
internal class Program
{

    static void Main(string[] args)
    {
        getit();
    }
    static async void getit()
    {
        HttpClient client = new HttpClient();
        var respo = await client.GetStringAsync("https://testnet.binancefuture.com/fapi/v1/klines?symbol=BTCUSDT&interval=1h&limit=10");
        Console.WriteLine(respo);
        
    }
}
Austin
  • 2,203
  • 3
  • 12
  • 28
  • 2
    While you need to await (or wait in some other way) result of async method (https://stackoverflow.com/questions/13636648/wait-for-a-void-async-method) presumably the code shown in the post is [MRE] and you just posted that as an example. Clearly from your question you` debugged that and confirmed that `respo` is actually assigned/printed. I'd recommend to [edit] the post fixing up the strange `async void`. At the same time consider showing Fiddler trace (or any other HTTP debugger) for that call as part of the question. – Alexei Levenkov Aug 21 '23 at 22:06

2 Answers2

2
  1. Don't forget that when you make a method asynchronous, its return type should (usually) be Task:

    static async Task getit()...
    
  2. Now that your method is asynchronous, you will need to await its result. This means you need to change your Main method to async Task too:

    static async Task Main(string[] args)...
    
  3. After all is said and done, you should end up with this, and this will run :)

    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await getit();
        }
    
        static async Task getit()
        {
            HttpClient client = new HttpClient();
            var respo = await client.GetStringAsync("https://testnet.binancefuture.com/fapi/v1/klines?symbol=BTCUSDT&interval=1h&limit=10");
            Console.WriteLine(respo);
        }
    }
    
  4. Having said this, I have a few improvement tips too!

    1. Move the Console.WriteLine to the Main method. This makes the getit do all the fetching, and the caller, do all the output. It's not necessarily what you want, but it felt right to me. It makes it re-usable for different output criteria!

    2. Follow naming conventions (make a method CapitalLikeThis). You don't have to, but it's something to note

    3. I think you might find that the namespace inclusion is not required here as they are typically part of the standard project set up... You could remove them if this inclusion is the case

    4. In C# 6 and onwards (Or something like that), you can also change your syntax to just say new eg. HttpClient client = new();. I quite like this syntax because it brings back full types and make's people's lives easier when reviewing code at a glance (although a controversial opinion).

    5. After all said and done, it will look like this:

      internal class Program
      {
          static async Task Main(string[] args)
          {
              string result = await GetIt();
              Console.WriteLine(result);
          }
      
          static async Task<string> GetIt()
          {
              HttpClient client = new();
              return await client.GetStringAsync("https://testnet.binancefuture.com/fapi/v1/klines?symbol=BTCUSDT&interval=1h&limit=10");
          }
      }
      

Why was what I did, a problem?

Hand-wavey explanation:

When an async task runs, a new CPU thread is set up. If that thread is not awaited, the program continues to run on past the line without a care in the world for what it might or might not return and so it gets to the end of your program and thinks nothing of it.

By adding the await and correctly stating that each method should expect an asynchronous task to run (marking it as a return type of Task), the program will wait for the thread's result before continuing on.

What's the point then?

In the specific example provided, one could argue that asynchronous programming might seem unnecessary or even overkill. If the sole purpose of the console application is to make a single HTTP request and wait for its result, then making it asynchronous doesn't bring any significant advantage. The overhead introduced by setting up the task and the continuation might not be justified.

The real power of asynchronous programming in C# shines in more complex scenarios:

  • UI Applications: In UI-driven applications, you don't want to freeze the interface while waiting for a lengthy operation. Async operations allow the UI to remain responsive.
  • Web Services: For services handling multiple requests, asynchronous programming can lead to better throughput and resource utilization.
  • Parallel Processing: If there are multiple independent operations (like multiple HTTP requests to different services), they can be started concurrently and awaited together, reducing overall processing time.

However, in simpler contexts, especially in straightforward console applications, the benefits of async/await might not be evident. It's essential to gauge the complexity of the application and the nature of the operations being performed before deciding to use async/await.

That said, even in simple applications, there's an argument for "future-proofing." As applications grow and evolve, what starts as a single HTTP request might later involve multiple calls, data processing, or other asynchronous operations. Starting with an asynchronous foundation can make such an evolution smoother.

Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233
  • Jimmyt1988 please consider to [edit] the question to match your accepted answer. @SwanPineapple clearly misinformed everyone of what is happening... and likely they will not be willing to fix the question themselves. – Alexei Levenkov Aug 21 '23 at 22:33
  • 1
    I personally have no problem with the question. It's clearly a new developer who needed a nudge in the right direction and it is laid out as clear as a new developer would find the tools to explain their problem. This answer's additional information helps others gain more from it than the explicit case. – Jimmyt1988 Aug 21 '23 at 22:35
1

I think you must await the method getit().

static async Task Main(string[] args)
// await getit();
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • While it is a good idea in general OP seem to claim that `respo` is actually assigned - so my guess they show bogus [MRE] rather than this being the main problem. – Alexei Levenkov Aug 21 '23 at 22:08