【问题标题】:ASP.NET: Stop code executionASP.NET:停止代码执行
【发布时间】:2015-06-29 19:38:26
【问题描述】:

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

有什么办法可以停止代码的执行,清理已经收集的数据?

最好的解决方案是拥有一个包含所有 jobID 的表,其中一点将确定代码是否可以继续并让用户通过按钮/链接进行更改。

【问题讨论】:

  • 重构您的设计以节省时间
  • 这是非常大的数据,所以需要一些时间
  • 您使用的是哪个版本的 .Net Framework?如果你在.Net 4.0中编程,那么你可以通过Tasks将耗时的任务推送到单独的线程上,然后使用TPL的任务取消功能。
  • 用户只需要取消自己正在进行的任务
  • 为什么不只检索前 10 行然后添加分页

标签: c# asp.net


【解决方案1】:

如果用户点击取消按钮,您可以考虑使用 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);
   }
}

【讨论】:

    【解决方案2】:

    您可以更改您的 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
    

    您的 UI 将自动刷新,对于完成状态,将出现报告图标,该图标将在新窗口中显示来自表格的报告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      相关资源
      最近更新 更多