2011-02-10 62 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;