问题描述:

I have been playing around with using Tasks with ASP.NET web forms with the aim of providing more detailed feedback of processes to the UI. My objective is to achieve the following:

  • A user clicks a button to do something.
  • The button click event starts a task to run asynchronously
  • The task then relays its progress to a label in the UI until it completes

I'm aware I could use a progress bar control to achieve something similar however I'm curious to see if it can be achieved in this way. My test code is as follows:

Aspx front end snippet:

<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"/>

The idea is that the timer will cause asynchornous postbacks which will output the status of the tasks progress to the label.

Aspx.cs snippets

I will use a static variable for testing purposes that the task will periodically update.

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

}

Despite the ReportProgress method firing correctly and updating the static variable, along with the timer event method firing correctly, the label in the update panel does not update until the task completes and shows the value of 9.

I've had success with a similar approach in the past where the task stored progress values in a database and the timer tick event simply retrieved and displayed it to the label. However I am curious to see if it is possible to achieve the same outcome without storing a progress value in the database.

I'd greatly appreciate any help or advice on this issue and thanks in advance :)

相关阅读:
Top