Calling a C# async WebMethod using jQuery's $.ajax() hangs endlessly

Viewed 2198

The Issue:

I'm attempting to call a C# Web Method from jQuery to update a user's profile.

When I implement async and await, the call is made to the Web Method but the call never completes. Chrome forever shows the response as "(Pending)", and the Timing tab shows that the call is "Stalled".

Any input is greatly appreciated.


I've Tried:

  • Not using async and await

    It works! However this entirely defeats the purpose of what I'm trying to achieve.


  • Changing Task<bool> to void:

    "An asynchronous operation cannot be started at this time."

    (Yes, my page is marked Async="true")


  • Googling and searching SO:

    I've found a few similar questions but the resulting answers were either "Just make it synchronous instead!" (which entirely defeats the purpose) or they were MVC solutions that I'd rather not employ in my current project.


Code:

$.ajax({
    type: "POST",
    url: "Profiles.aspx/updateProfileName",
    data: JSON.stringify({
        profileName: $input.val(),
        customer_profile_id: cp_id
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: callSuccessful,
    error: callFailed
});
[WebMethod]
public static async Task<bool> updateProfileName(string profileName, string customer_profile_id)
{
    User user = (User) HttpContext.Current.Session["user"];
    if (profileName.Trim().Length == 0) return false;
    int customerProfileId = int.Parse(customer_profile_id);

    CustomerProfileViewModel profile = new CustomerProfileViewModel();
    profile.profile_name = profileName;
    profile.customer_profile_id = customerProfileId;
    profile.customer_id = user.customerId;

    bool profileUpdated =  await ExampleApi.UpdateProfile(profile);
    return profileUpdated;
}
3 Answers

Pretty sad after 2 years nobody has provided an answer. Basically:

bool profileUpdated =  await ExampleApi.UpdateProfile(profile).ConfigureAwait(false);

This configures the task so that it can resume on a different thread than it started on. After resuming, your session will no longer be available. If you don't use ConfigureAwait(false), then it waits forever for the calling thread to be available, which it won't be because it is also still waiting further back in the call chain.

However, I run into a problem where the return value doesn't get sent. the asp.net engine that calls the WebMethod is supposed to await the result if Async=true, but that doesn't seem to happen for me.

In this line>

bool profileUpdated = await ExampleApi.UpdateProfile(profile);

This method must also be static and asynchronous, in addition to all others that follow the call stack.

Another important point is to mark your ajax call with async: true,

Related