2011-02-10 61 views
8

在ASP.NET MVC中的异步控制器中,有什么方法可以告诉客户端是否/何时中止请求?检测ASP.NET MVC中的中止请求

[NoAsyncTimeout] 
public void IndexAsync() { 
    var source = new CancellationTokenSource(); 

    Task.Factory.StartNew(() => { 
    while (true) { 
     if (source.Token.IsCancellationRequested) { 
     AsyncManager.Finish(); 
     return; 
     } 

     Response.Write("."); 
     Thread.Sleep(1000); 
    } 
    }, source.Token); 

    // Is there any way to do this? 
    Request.Aborted += (sender, e) => source.Cancel(); 

    AsyncManager.OutstandingOperations.Increment(); 
} 
+1

[检测异步客户端断开连接在ASP.NET MVC]的可能重复(http://stackoverflow.com/questions/4772597/detecting-async-client-disconnect-in-asp- net-mvc)我刚刚也发现了这个问题,它也会回答你的问题以及其他一些信息。 – 2011-02-10 22:08:35

回答

8

有关使用

HttpContext.Current.Response.IsClientConnected 

从一个非常基本的测试这似乎是什么不为中止Ajax请求工作。 MSDN暗示它应该。

+0

我在while循环中使用同步上下文,它完美地工作,允许在结束响应之前处理进程,流或缓存文件。 – 2012-10-05 07:13:25

2

尝试

CancellationToken clientDisconnectedToken = HttpContext.Response.ClientDisconnectedToken;