ASP.NET:停止代码执行

时间:2011-11-24 12:55:56

标签: c# asp.net

我有一个ASP.NET网站,用户通过点击按钮从数据库获取大数据,但有时用户想要取消作业(这些工作可能需要很长时间)并且他们的会话将在做这份工作。

有没有办法停止执行代码并清理已经收集的数据?

是一个包含所有jobID的表的最佳解决方案,其中一位将确定代码是否可以继续并让用户从按钮/链接更改此内容。

2 个答案:

答案 0 :(得分: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>

只需将数据库查询放在相应的服务器端eventHandler

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);
   }
}

答案 1 :(得分:0)

您可以更改UI以允许用户提交请求并取消现有请求,然后将用户请求保存在某个表中(将具有状态列) 你可以编写一个Windows服务

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

您的用户界面将自动刷新,对于已完成状态,将显示报告图标,该图标将在新窗口中显示来自表格的报告。

相关问题