c# - UpdatePanel 从 ajax 刷新调用不同的线程
问题描述
我有一个可以进行 ajax 调用的按钮。
<%@ Page Language="C#" MasterPageFile="~/pj.master" AutoEventWireup="true" CodeFile="refreshData.aspx.cs" Inherits="Admin_refreshData" EnableEventValidation="false" %>
<%@ MasterType VirtualPath="~/pj.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<asp:ScriptManager ID="scriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function checkSubmit()
{
if (confirm('Are you sure you want to refresh the data?')) {
//Disable our button
$('#<%: butSubmit.ClientID %>').attr("disabled", true);
<%= ClientScript.GetPostBackEventReference(butSubmit, string.Empty) %>;
$.ajax({
error: function (data) {
//The Ajax request was a failure.
alert('Fail to call batch job.');
},
success: function (data) {
$('#<%: lblMsg.ClientID %>').text('Batch job running. Please kindly wait.');
},
complete: function () {
}
});
}
else
return false;
}
</script>
<h1>Refresh Data</h1>
<asp:Panel ID="PnlSearch" runat="server">
<asp:UpdatePanel ID="updtPnlRefresh" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table border="0" style="width: 100%">
<tr>
<td>
Refresh Data: <asp:Button ID="butSubmit" runat="server" Text="Refresh" OnClientClick="return checkSubmit()" UseSubmitBehavior="false" OnClick ="butSubmit_Click" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</asp:Content>
然后在我的后端,当单击提交按钮时,它将开始另一个耗时的过程。所以我把这个过程分成另一个任务。然后在任务完成后,我想更新结果。但这似乎不起作用。
后面的代码:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butSubmit_Click(object sender, EventArgs e)
{
new System.Threading.Tasks.Task(RunBatchJob).Start();
lblMsg.Text = "Batch job running. Please kindly wait.";
butSubmit.Enabled = false;
}
private void RunBatchJob()
{
string path = @"D:\Codes\RefreshData.exe";
Master.RemoveErrorMessage();
if (File.Exists(path))
{
Process process = new Process();
process.StartInfo.FileName = path;
process.Start();
process.WaitForExit();
int result = process.ExitCode;
if (result == 0)
Master.AddSuccessMessage("Batch job successfully run.");
else
Master.AddErrorMessage("Batch job failed to run properly.");
}
else
{
Master.AddErrorMessage("Batch job file not found.");
}
lblMsg.Text = "";
butSubmit.Enabled = true;
}
因此,当该过程完成后,我想删除状态文本并重新启用按钮。但它仍然存在,并且该按钮仍然被禁用。
如何解决这个问题?
解决方案
您可以使用 SignalR 将更改推送回客户端。它会自动选择最有效的协议(即 Websockets、LongPolling 等)
或者,当您启动任务时,在表中放置一个条目并将主键返回给客户端。客户端可以使用计时器继续轮询以查看表中的状态是否已更改并采取适当的措施。
要检索状态,您可能必须在页面中公开新代码。
推荐阅读
- puppeteer - 使用 puppeteer 抓取 wish.com
- android - 如何将从服务器获取的数据传递到android中的意图?
- shopware - Storefront Shopware 6.1 中的自定义 scss
- .net - 使用对象引用与标识符作为集合键
- python - 如果搜索产生的结果多于显示的结果,则抓取隐藏页面
- vue.js - Vue v-model 未显示正确的默认值
- html - 在 chrome 中禁用或更改“保存用户名/密码”提示的行为
- java - 无法访问 foo 类型的封闭实例。为什么?
- python - 在 tkinter 中使用从一个类到另一个类的变量
- firebase-analytics - 我最终在 Firebase Analytics 控制台中丢失了一些数据