开发者

Catching the abort in a WebMethod when calling XHR.abort()

Summary: I would like to be able to catch the XHR.abort() in a WebMethod to stop executing server-side code as soon as possible.

I have a webmethod, similar as follows:

[WebMethod]
public static string GetHello()
{
    System.Threading.Thread.Sleep(5000);
    return "{\"result\":\"Hello!\"}";
}

On the page I call this method with the following javascript (jQuery) code:

var lastXHR = null;

function doCall() {

    if (lastXHR != null)
        lastXHR.abort();

    lastXHR = $.ajax({
        url: "default.aspx/GetHello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        type: 'POST',
        error: function (jqXHR, textStatus, errorThrown) {
            if (textStatus.statusText == "abort") {
                // I know this was aborted here
                // Code omitted for simplicity
            }
        },
        success: function (data, textStatus, jqXHR) {
            var d = $.parseJSON(data.d);
            alert(d.result);
        },
        complete: function (xhr, status) {
            lastXHR = null;
        }
    });
}

I am able to handle the abort() quite easily with this code on the client, but I would like the web server to stop executing GetHello() when the XHR is aborted.

The reason I need to do this is because on the server side in my project I am calling a search on a database, which can potentially take many seconds to complete, and calling SqlCommand.Cancel() would be very beneficial to my IT team ;-)

UPDATE: I'm going to try calling a secondary WebMethod whose sole purpose is to indicate that the previous call from the same client is to be cancelled. Will post this as an answer if it works.开发者_运维问答

Other ways to do this would be much-appreciated though!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜