Share via


Call a WEB API Synchronously

Question

Thursday, March 16, 2017 12:09 PM

Hi,

I am trying to call the Jenkins WEB API from my DOTNET application. It needs a HTTP Post method and using HTTPClient instead of WebRequest. 

By default the Service calls are Asynchronous. But in my case, I want to wait till the Job completes and if possible show the log in my application. 

I tried with

var PostTask= Task.Run =>****

PostTask.Wait()

But this didn't work. Can someone help me on this?

Thanks

~Biswajit Pattanaik

Thanks n Regards Biswajit Pattanaik

All replies (4)

Friday, March 17, 2017 2:59 PM âś…Answered

You should consider using WebClient which supports all the HTTP verbs and is commonly used to communicate with REST APIs. You can use whichever method is most appropriate for your need but I suspect that you're getting JSON back therefore UploadString is probably the method you'd want to use. You don't actually need to post any data but if the API requires a JSON body, that's what you'd pass. What you get back is the response. There are both sync and async versions so use whichever one is most appropriate for your needs.

If you need to wait for an async task to complete then you can use Wait but this blocks the caller. If you're using async/await then use an await on the async call instead.

Task SomeAsync ()
{
   ...
}

async Task CallSomeAsync ()
{
   await SomeAsync();

   //Won't run until SomeAsync completes
}

If your method isn't async then use ContinueWith on the returned task from the async call.

Task SomeAsync ()
{
   ...
}

void CallSomeAsync ()
{
   SomeAsync().ContinueWith(() => {
      //Won't run until SomeAsync completes
   });
}

Michael Taylor
http://www.michaeltaylorp3.net


Friday, March 17, 2017 7:27 AM

Hi Biswajit Pattanaik.

This forum is for on-premises TFS, I help you move this case to C# forum for dedicated help.

Thank you for your understanding.

Best regards

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Tuesday, March 21, 2017 9:54 AM

Thanks Michael. I tried this and could solve many of the problems I was facing. In one of the methods I do a Thread.Sleep() for 3/4 seconds and continue the loop, till I get a true value from service. This works well when I execute the application.

But when, I add the same into a TFS build definition as a task, the Sleep and while loop doesn't seem to be working.

Thanks n Regards Biswajit Pattanaik


Tuesday, March 21, 2017 11:48 AM

Sorry, It was my bad, its working now. Thanks Michael for the help.

Thanks n Regards Biswajit Pattanaik