简体   繁体   English

ajax.abort()的ASP.NET MVC解决方法

[英]ASP.NET MVC workaround for ajax.abort()

I have a rest endpoint on asp.net mvc: 我在asp.net mvc上有一个休息端点:

[HttpGet]
public List<SomeEntity> Get(){
    // Lets imagine that this operation lasts for 1 minute
    var someSlowOperationResult = SomeWhere.GetDataSlow();
    return someSlowOperationResult;
}

On the frontEnd I have a next javascript: 在前端我有一个下一个javascript:

var promise = $.get("/SomeEntities");
setTimeout(function(){promise.abort()}, 100);

How to force Thread to die after abort call, to prevent slow calculation to be done? 如何在中止调用后强制Thread死掉,以防止slow计算?

Thanks in advance. 提前致谢。

I found that Response have isClientConnected property. 我发现ResponseisClientConnected属性。 So we can use next approach: 所以我们可以使用下一个方法:

[HttpGet]
public List<SomeEntity> Get(){
        var gotResult = false;
        var result = new List<SomeEntity>();
        var tokenSource2 = new CancellationTokenSource();
        CancellationToken ct = tokenSource2.Token;
        Task.Factory.StartNew(() =>
        {
            // Do something with cancelation token to break current operation
            result = SomeWhere.GetSomethingReallySlow();
            gotResult = true;
        }, ct);
        while (!gotResult)
        {
            if (!Response.IsClientConnected)
            {
                tokenSource2.Cancel();
                return result;
            }
            Thread.Sleep(100);
        }
        return result;
}

Can we? 我们可以吗? Or I miss something? 或者我想念什么?

UPDATE:

Yes, it works 是的,它有效

The backend has no idea that you have called abort() and if the request has already been sent then the server-side logic will run until it completes. 后端不知道你已经调用了abort() ,如果已经发送了请求,那么服务器端逻辑将一直运行直到它完成。 In order to stop it from running you will have to send another request to your controller which notifies that controller that you've aborted the request and the controller will have to access the instance that is currently running you slow operation and this instance should have a method which forces the calculations to cancel. 为了阻止它运行,你必须向你的controller发送另一个请求,通知控制器你已经中止了请求,控制器必须访问当前运行速度慢的实例,这个实例应该有一个强制计算取消的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM