-2

I am trying to consume an API I developed in NODE.js, I am doing this from a c# windows forms desktop application.

The API is written ASYNC on the sever side but can it be sync inside my client? Let me explain what I mean.

This is a code sample of what I am doing:

public static DateTime GetDateTime()
{
    try
   {
        string result = Task.Run(() => 
        client.GetStringAsync(client.BaseAddress)).Result;
        Date currentTime = JsonConvert.DeserializeObject<Date>(result);
        return currentTime.Value;
    }
   catch (Exception ex)
   {
       throw ex;
   }

}  

Later in the program I call this function:

DateTime currentDate = GymAPI.GetDateTime();

According to what I researched this runs synchronously... and this is what I need because after the function call I use the datetime to calculate and display the age of a list of persons.

As I understand, if i use ASYNC/AWAIT, the code that calculates the age of the persons will execute right away while most likely I will not have yet the value of the current date. Am I correct in this assumption?

Do I need to run anything ASYNC in my app other than when I am sending an email (takes like 5 seconds) and I want the sendmail task to run in the background while the app remains responsive to the user?

Finally, and more important, the above code seems to work but... Is the way I did it the best practice to make the call run synchronously? No deadlocks? Thanks for your patience reading this but I found a lot of posts and honestly I couldn't find all the answers.

If there are too many questions please only answer the last one! :)

Max
  • 1
  • 3
  • What type of application? Console? WinForms? WPF? – John Wu Apr 15 '19 at 05:43
  • 1
    Too many questions for single StackOverflow question. – vasily.sib Apr 15 '19 at 05:48
  • Windows Forms! Sorry for so many questions, if possible only answer the last one about it being the best way to make it sync. – Max Apr 15 '19 at 05:54
  • 2
    No, async doesn't mean the code will continue without waiting for the result of the call. – CodeCaster Apr 15 '19 at 06:00
  • 1
    `var result = Task.Run(() => DoSomethingAsync()).Result;` may cause a deadlock in a various situations. Just google a little for _"c# run async method synchronously"_. – vasily.sib Apr 15 '19 at 06:18
  • @codeCaster Then what do they mean in this page? https://www.codingame.com/playgrounds/4240/your-ultimate-async-await-tutorial-in-c/benefits-of-asynchronous-using-async-await – Max Apr 15 '19 at 06:23
  • 1
    If the only reason you want to do it synchronously is because you think the code will continue to run and not wait, don’t. It will wait, that’s the whole point of `await`. Just use the async way and don’t try to force it into sync. Unless the `client` has a sync method also which often is the case. Also server side doesn’t matter, it can be sync or async and the client can do whatever it wants regardless. – Sami Kuhmonen Apr 15 '19 at 06:26
  • 1
    http://blog.stephencleary.com/2012/02/async-and-await.html – Paulo Morgado Apr 15 '19 at 08:06
  • http://msdn.microsoft.com/en-us/library/hh873175.aspx – Paulo Morgado Apr 15 '19 at 08:06

1 Answers1

-1

So I was fundamentally confused and I was not grasping the ASYNC/AWAIT/TASK relationship... But now I think is much more clear.

I followed advise and went for the ASYNC way following the example inside this link: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

I rewrote everything like this in case someone cares:

        public static async Task<DateTime>GetDateTime()
        {
            using (HttpClient client = new HttpClient())
            {
                // Omitted some code here for simplicity.
                try
                {
                    string result = await client.GetStringAsync(client.BaseAddress);
                    Date currentTime = JsonConvert.DeserializeObject<Date>(result);
                    return currentTime.Value;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
        }

Basically you can run Tasks ASYNC so when you call the function GetDateTime() you will start running the task without blocking the code below from execution like this:

Task<DateTime> getCurrentDate = MyClass.GetDateTime();
//Code here executes right away without waiting for the task to finish

In this case I started the task inside the constructor and awaited for it right before I was going to need the result like this:

DateTime result = await getCurrentDate;

Or you can start and await for the task to finish in the same line of code:

DateTime result = await MyClass.getCurrentDate();

With the method above it looks synchronously but you don't really take advantage of running one or more task while your other code executes.

Max
  • 1
  • 3
  • You're still [very much missing the point](https://stackoverflow.com/a/9519578/542251). You confusing blocking with parallel processing, they are not the same thing – Liam Apr 15 '19 at 12:40
  • @Liam Thanks for the link, I read it and they are mainly discussing await vs wait. I think I see what you mean, it's my bad for saying non-blocking the code when in fact is a parallel process but I learned more about this here https://stackoverflow.com/questions/2625493/asynchronous-vs-non-blocking again thanks for the input. – Max Apr 16 '19 at 14:29