Reputation: 13135
I can't get this BackgroundWorker to work for me. I'm using m3rLinEz's example from here
The problem is that the GUI does not respond and the percentage is not updating.
I'm using a master page and I've set async="true"
in the header of the content page.
Am I missing something else?
ASPX Code:
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnClick_Go" />
<asp:Label runat="server" id="textUpdate" text="0%" />
code behind
protected void btnClick_Go(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
// this allows our worker to report progress during work
bw.WorkerReportsProgress = true;
// what to do in the background thread
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs args)
{
BackgroundWorker b = o as BackgroundWorker;
// do some simple processing for 10 seconds
for (int i = 1; i <= 10; i++)
{
// report the progress in percent
b.ReportProgress(i * 10);
Thread.Sleep(1000);
}
});
// what to do when progress changed (update the progress bar for example)
bw.ProgressChanged += new ProgressChangedEventHandler(
delegate(object o, ProgressChangedEventArgs args)
{
textUpdate.Text = string.Format("{0}%", args.ProgressPercentage);
});
// what to do when worker completes its task (notify the user)
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate(object o, RunWorkerCompletedEventArgs args)
{
lblSuccess.Visible = true;
});
bw.RunWorkerAsync();
}
Upvotes: 1
Views: 429
Reputation: 1499740
BackgroundWorker
is usually used with client-side UIs - WPF, WinForms etc.
In your code, you're trying to update the UI after the response has been sent back to the client. How do you expect that to work without a later request from the client to the server?
When it comes to web applications, you'll need to use AJAX to keep updating the UI. There may well be nice ways of making that AJAX easy to manage, but you can't just use BackgroundWorker
on the server side and hope it'll all work.
Upvotes: 2