2011-11-24 237 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在完成状态时,将出现将在新窗口中显示来自表格的报告的报告图标。