I'm trying to understand how to call from jquery 1.9.1 a .net 4.5 web service (asmx) which is using async/await. The js code is classic:
$.ajax({
type: "POST",
url: "ws/UpdCategory",
data: strData,
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: saveCategory_onComplete
});
the web service in ws.cs, code behind of ws.asmx:
[WebMethod]
public async Task<int> UpdCategory(string jsonData)
{
JsonGenericResponse objWmJson = new JsonGenericResponse();
objWmJson.IsInError = "true";
try
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
Dictionary<string, string> objDict = objJss.Deserialize<Dictionary<string, string>>(jsonData);
DataIfCloudEspresso objData = new DataIfCloudEspresso();
//
StringBuilder objBuilder = new StringBuilder();
objBuilder.Append("<?xml version=" + (char)39 + "1.0" + (char)39 + " encoding=" + (char)39 + ConfigurationService.XMLEncoding + (char)39 + "?>");
objBuilder.Append("<Category>");
.....various fields
objBuilder.Append("</Category>");
// the row below call the method on Data Access Layer
int updatedCount = await objData.UpdCategory(objBuilder.ToString());
return updatedCount;
}
}
and finally the DAL method:
public async Task<int> UpdCategorieArticoli(string xmlData)
{
try
{
using (SqlConnection objConn = new SqlConnection(base.ConnectionString))
{
using (SqlCommand cmdADO = new SqlCommand("spUpd_Category", objConn))
{
cmdADO.Parameters.Add(new System.Data.SqlClient.SqlParameter("@XMLDoc", SqlDbType.Text));
cmdADO.Parameters["@XMLDoc"].Value = xmlData;
cmdADO.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", SqlDbType.Int));
cmdADO.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
//
cmdADO.CommandType = CommandType.StoredProcedure;
//
await objConn.OpenAsync().ConfigureAwait(false);
return await cmdADO.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
}
catch (Exception)
{
throw;
}
finally
{
}
}
The problem is this: the DAL method if is called from a Page_Load , for example, works without problems; instead when called from the web service (which is called from javascript) the code hangs on the line await cmdADO.ExecuteNonQueryAsync().
I suppose that the problem is the context switch from the client (the js code from the browser) and the code behind that works on the server, i don't understand how to solve this issue. I have tried various code found googling , but no solution.
The obvious scope is to maximize the use of async code for the max performance.
I have tried to write an old style BeginExecuteNonQuery with a callback, but i have not found a solution on how to communicate the result to the calling web service from the EndExecuteNonQuery.
await objData.UpdCategory(objBuilder.ToString())andUpdCategorieArticoli(string xmlData)?