Converting the Async Machine Learning C# code to Sync

In some scenarios we need synchronous code, for example server code, web services, proxy, etc.

In the case of Azure Machine Learning we have web service sample code which is generated for us by the Azure Machine Learning Studiohttp://ift.tt/1AHmmIU with C# code with asynchronous calls.

Azure ML generated code

Now with a few little tweaks, we can convert this generated code to be synchronous simply by removing all the async and await methods.

The first line of code that we have to edit is the PostAsync method, which is used to send the data to the Machine Learning service:

HttpResponseMessage response = await client.PostAsJsonAsync(“”, MyRequest);

to this one:

HttpResponseMessage response = client.PostAsJsonAsync(string.Empty, MyRequest).Result;

Notice we completely remove the await command and put after the parenthesis the .Result object to change this line for an a synchronous call, also used the string.Empty instead the just for coding conventions.

The next line will be a JSON response which the ML studio sample code shows as:

string result = await response.Content.ReadAsStringAsync();

This line we will edit and our final result will be this one:

string result = response.Content.ReadAsStringAsync().Result;

Just exactly the same modifications as our prior step.

The result will be in JSON format, and we can use the Newtownsoft library in order to parse the JSON string into a .Net object. For more information about JSON.Net click here:

The last step will be changing the method result from

static async Task InvokeRequestResponseService()

To:

static void InvokeRequestResponseService()

or even we can actually return the value from the JSON output already parsed into a .net object for example

static List InvokeRequestResponseService()

To wrap this short post up, these steps are all we need to render the ML Studio-generated code synchronous. I should add that this is not a method to be recommended for client software, as synchronous calls will block the UI until the process completes. However for server code, web services, or proxies these simple steps can be an invaluable tool to have in your belt.

Leave a Reply