How to explode a .NET developer, give them this challange:

Write a method.
- I must HTTP Get any site (does not matter what), and return the result
- It must NOT be async, and must directly return the result string (No Task<string>)
- It must use HttpClient
- It must be in .Net framework 4.5 or lower
- No other nuget packages allowed

This was my job today and i want you to share my pain!

  • 2
    So... No curl?
  • 2
    @atheist i was legitematly tempted to drop out of the .net environment entirely and use something like Curl yes, but i was told no :/
  • 1
    @Heliarco So... You're reimplimenting curl in c#? The source code is on github! It's only a few... Uhhh... Lots of files.
  • 2
    Final result was:

    var task = Task.Run(() => _c.SendAsync(request));


    var response = task.Result;


    var task2 = Task.Run(() => response.Content.ReadAsStringAsync());


    var content = task2.Result;

    Its shit for UI applications as far as i understand, but in a console it works
  • 2

    Working in a synchronous part of a sharepoint 2013 plugin
  • 2
    Can you not simplify those even further? From the docs:

    Accessing the [Result] property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

    So you should be able to save those two Wait calls.

    And why wrap the requests in Task.Run? Maybe you can directly use .Result on SendAsync / ReadAsStringAsync?
  • 1
    @Heliarco ahhhh... Sync-asyn bridges are a bitch.
  • 1
    @gof6yogy from my expierence this would have worked too. Wrapping it in tasks was useless as a task is returned as is.

    I also remember an extension method of RunSynchronously exists but I don't remember the difference between RunSyncronously vs accessing Result directly.
  • 1
    @demortes I am very tempted to agree with you, but whenever you dig into the issue of bridging async to sync, you get a thousand different cargo cult'ish solutions and advice. Honestly the lack of a clear and concise example from MS is the issue here. It just seems so half baked.

    And yes, i love async programming, but the elephant in the room is that there is just a lot of legacy systems that can't be retrofitted to support async and that means we purposefully just cut them off from support.
  • 0
    @Heliarco don't forget there are a lot of tasks that are inherently synchronous. Trying to do them async just adds overhead and complexity and 0 performance gain (tiny loss even).
  • 0
    Oooohhh sharepoint plugins fun… yeah I feel you. This hits too close to home for my liking
Add Comment