C# 使用异步任务ASP.NET C更新更新面板

C# 使用异步任务ASP.NET C更新更新面板,c#,asp.net,webforms,updatepanel,task,C#,Asp.net,Webforms,Updatepanel,Task,我一直在尝试使用ASP.NET web表单中的任务,目的是向UI提供更详细的流程反馈。我的目标是实现以下目标: 用户点击一个按钮来做某事。 按钮单击事件启动异步运行的任务 然后,任务将其进度中继到UI中的标签,直到完成为止 我知道我可以使用进度条控件来实现类似的功能,但是我很好奇是否可以通过这种方式实现。我的测试代码如下: Aspx前端代码段: <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional

我一直在尝试使用ASP.NET web表单中的任务,目的是向UI提供更详细的流程反馈。我的目标是实现以下目标:

用户点击一个按钮来做某事。 按钮单击事件启动异步运行的任务 然后,任务将其进度中继到UI中的标签,直到完成为止 我知道我可以使用进度条控件来实现类似的功能,但是我很好奇是否可以通过这种方式实现。我的测试代码如下:

Aspx前端代码段:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="500" OnTick="Timer1_Tick"></asp:Timer> 
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="Button1" />
    <asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Push Me"/>
其思想是计时器将导致异步回发,从而将任务进度的状态输出到标签

Aspx.cs代码段

我将使用静态变量进行测试,任务将定期更新

public static int testing;

protected void Button1_Click(object sender, EventArgs e) {
    //Initialise static
    testing = 0;

    var progress = new Progress<int>(ProgressReport);
    Task t = new Task(() => Test(progress));
    t.Start();
 } 

public void ProgressReport(int progress)
{
    //Update the static with the current progress value
    testing = progress;            
}

public void Test(IProgress<int> progress)
{
    for (int i = 0; i < 10; i++)
    {
        //Pretend to do something intensive
        Thread.Sleep(1000);
        //Output the progress
        progress.Report(i);
    }
}

protected void Timer1_Tick(object sender, EventArgs e)
{
    //Output the value of the static to the label
    Label1.Text = testing.ToString();
}
尽管ReportProgress方法正确触发并更新静态变量,以及计时器事件方法正确触发,更新面板中的标签在任务完成并显示值9之前不会更新

我曾经成功地使用过类似的方法,其中任务将进度值存储在数据库中,而计时器滴答声事件只是检索并将其显示在标签上。然而,我很想知道,如果不在数据库中存储进度值,是否有可能实现相同的结果

我非常感谢您在这个问题上提供的任何帮助或建议,并提前表示感谢:

使用线程的任何原因。在等待任务之前先睡一觉。延迟,我很好奇。