gpt4 book ai didi

c# - asp.net 而第一个请求处理允许点击第二个请求

转载 作者:太空狗 更新时间:2023-10-29 23:28:35 25 4
gpt4 key购买 nike

在 Asp.net Web Form 应用程序中,我有“生成报告”按钮和一个“取消”按钮来取消报告生成过程,如果它需要很长时间的话。

当我点击“生成报告”时,它会执行繁重的任务,3 秒后我尝试通过点击“取消”按钮来取消这个繁重的任务。

但在一段时间延迟后调用取消按钮单击的服务器端代码。

我什至尝试在 JavaScript 中使用 window.stop() 来停止页面加载并快速访问服务器代码,但仍然存在延迟。

代码:

protected void btnExportExcel_Click(object sender, EventArgs e)
{

// Doing Heavy Task to Generate Report

}


protected void btnCancel_Click(object sender, EventArgs e)
{
if (Response.IsClientConnected)
{

HttpContext.Current.ApplicationInstance.CompleteRequest();

}
}

<asp:Button ID="btnCancel" runat="server" Text="Cancel Request"

OnClientClick="return StopPageLoading();" OnClick="btnCancel_Click" />


function StopPageLoading() {

try
{
window.stop();
} catch (exception)
{
document.execCommand('Stop'); // for IE and other browsers
}

}

当当前请求正在处理中时,我如何允许快速启动另一个请求?

如何让 UI 响应?

更新:

重现情况:

  1. 我单击“导出到 Excel”,处理需要 7 分钟。
  2. 在处理过程中,我单击“取消”按钮,但又需要 5 分钟才能取消。

我读到 Concurrent request在 Asp.NET 中是不可能的,因为 session 状态会产生独占锁。

那么如何快速取消呢?

使我的方法async 是否有助于克服 session 状态独占锁问题?

最佳答案

another question从你这里,你可以这样做

public partial class Contact : Page
{

private static CancellationTokenSource tokenSource = new CancellationTokenSource();


protected void Page_Load(object sender, EventArgs e)
{

}

protected async void btnExportExcel_Click(object sender, EventArgs e)
{
CancellationToken cToken = tokenSource.Token;
cToken.Register(() => cancelNotification());

try
{

await Task.Run(() =>
{
cToken.ThrowIfCancellationRequested();

GenerateReport(sender, cToken);

}, cToken);
}
catch(OperationCanceledException)
{

}
}

private void GenerateReport(object sender, CancellationToken ct)
{
// Just to Simulate Export to excel

Thread.Sleep(70000);
}


protected void btnCancel_Click(object sender, EventArgs e)
{

tokenSource.Cancel();

}


private static void cancelNotification()
{
// Do your stuff when the user is canceld the report generation

}
}

在你的 Page.aspx

需要这样的东西

<%@ Page Async="true" EnableSessionState="false" %>

希望对你有帮助!

关于c# - asp.net 而第一个请求处理允许点击第二个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51324184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com