2011-11-24 186 views
0

我有一個ASP.NET網站,用戶通過單擊按鈕從數據庫獲取大量數據,但有時用戶想要取消作業(這些作業可能需要很長時間),他們的會話將在執行此項工作時掛起。ASP.NET:停止代碼執行

有什麼辦法可以停止執行代碼並清理已經收集的數據嗎?

是一個帶有所有jobID的表格的最佳解決方案,其中一位確定代碼是否可以繼續,並讓用戶從按鈕/鏈接改變它。

+0

重構您的設計不需要時間 –

+0

這是非常大的數據,因此需要一些時間 – Millerbean

+0

您正在使用哪個版本的.Net Framework?如果您使用.Net 4.0進行編程,那麼您可以通過任務在單獨的線程上推送耗時的任務,然後使用TPL的任務取消功能。 –

回答

0

如果用戶點擊取消按鈕,您可以考慮使用AJAX並中止當前的請求。

<asp:ScriptManager ID="ScriptManager1" runat="server"> 
    </asp:ScriptManager> 
    <script type="text/javascript" language="javascript"> 
     var sm = Sys.WebForms.PageRequestManager.getInstance(); 
     sm.add_initializeRequest(initRequest); 

     function initRequest(sender, args) { 
      if (sm.get_isInAsyncPostBack() && 
       args.get_postBackElement().id == 'btnStart') { 

       args.set_cancel(true); 
       alert('Still progressing!\nPlease wait ...'); 
      } else if (sm.get_isInAsyncPostBack() && 
         args.get_postBackElement().id == 'btnCancel') { 
       sm.abortPostBack(); 
      } 
     } 

    </script> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
     <ContentTemplate> 
      <asp:UpdateProgress ID="UpdateProgress1" runat="server"> 
       <ProgressTemplate> 
        <p>Processing....</p> 
        <asp:LinkButton ID="btnCancel" runat="server">Cancel</asp:LinkButton> 
       </ProgressTemplate> 
      </asp:UpdateProgress> 
      <asp:LinkButton ID="btnStart" runat="server" onclick="btnStart_Click">Start work!</asp:LinkButton> 
     </ContentTemplate> 
    </asp:UpdatePanel> 

只要把數據庫查詢在相應的服務器端事件處理程序

public partial class asyncLongLasting : System.Web.UI.Page 
{ 
    protected void btnStart_Click(object sender, EventArgs e) 
    { 
     // your database query may start here 
     System.Threading.Thread.Sleep(5000); 
    } 
} 
0

你可以改變你的用戶界面,允許用戶提交他們的要求加上取消現有請求,然後保存在一些表中的用戶請求(將有一個狀態欄) 你可以寫一個窗口服務,將

1)read all the request (cancel or data) from users 
2)for data request it will create a job and start the job and change the status of request (with in process) 
3)for cancle it will stop the job and change the status with stoped 
4)when the job will finished it will create the report in other table and change the status with complete 

你的用戶界面將自動刷新FO在完成狀態時,將出現將在新窗口中顯示來自表格的報告的報告圖標。