0

I have a ASP.NET web service (.asmx) that is called from client side with JavaScript.

Let say that the web service has a web method with the name "GetTotalMovies()". This web method will return an int with the number of movies in a specific channel on YouTube.

When this web method is called it will do a http request to the YouTube REST API to get how many movies a specific channel has and then return it to the client that called "GetTotalMovies()".

The call the the YouTube REST API is pretty slow so I want to do this asynchronous with this "pseude" code:

private async Task<int> GetTotalMoviesFromYouTubeApi()
{
     using(var client = new WebClient()) {
         return await client.DownloadStringAsync(_uri);
     }
}

And here is my web method that is called from the client:

[WebMethod]
public int GetTotalMovies() {
    return (int)await PostDataToYouTubeApi(s);
}

This will not work since I use the await keyword in the method GetTotalMovies when the method is not async.

But if I change the method to async I need to return Task from the method. And when I change this it will be really messy when JavaScript call this function.

I am stuck, I don't really now how to go further. Help! :)

Delta
  • 171
  • 11
  • 1
    Javascript will not synchronously wait for a web method to complete, it has no concept of if your code uses the `async/await` pattern or not. Standard behavior in javascript is to use a callback to continue execution once the web results are in. In short, if you can't write async methods then just use the standard synchronous approach. – Igor Mar 01 '16 at 18:13
  • So I can make the http request to YouTube synchronously in good conscience? – Delta Mar 01 '16 at 18:23
  • 1
    @Delta - correct. Async/Await has nothing to do with parallel programming or making the call faster. It is a server side only technique to allow the O/S to reuse a thread while the code execution is waiting for I/O to compete. The javascript client code will never know the difference one way or the other. – Igor Mar 01 '16 at 18:29
  • Ok, so in short a call from JavaScript to a web method will always block the request thread until the web method response? And therefore it is no idea to try making async/await in these circumstances. – Delta Mar 01 '16 at 18:40
  • 1
    @Delta - i am not sure what you are asking. In javascript a http/web call is done asynchronously using callbacks for when the call completes. The code will continue to execute and the browser/client stays responsive. This happens always and has no bearing on if you use async/await in your c# code. (*side note - yes it is actually possible to call a web method/service and wait it synchronously but it is not recommend and I have yet to see actual code in production that does this because it hoses the browser*) – Igor Mar 01 '16 at 19:11

0 Answers0