Discussion:
Updating UI from another thread
(too old to reply)
x***@y.com
2018-12-29 19:04:07 UTC
Permalink
I have a long running operation running on the UI thread.
I want to show a progress bar while this operation is running.

The basic structure I have is below.
I want the timer event and update of the progress bar to happen on a
different thread or task while the long operation is running.
I should also mention that the long running operation also updates
other parts of the UI as it runs.

Can this be done?


private void btnStart_Click(object sender, EventArgs e)
{
StartProgressBar();

// start long running operation

StopProgressBar();
}

private void StartProgressBar()
{
tmrProgress.Enabled = true;
}

private void StopProgressBar()
{
tmrProgress.Enabled = false;
}

private void tmrProgress_Tick(object sender, EventArgs e)
{
if ((progressBar1.Value + 10) > progressBar1.Maximum)
{
progressBar1.Value = progressBar1.Minimum;
}
else
{
progressBar1.Value += 10;
}
}
Arne Vajhøj
2018-12-30 00:18:32 UTC
Permalink
Post by x***@y.com
I have a long running operation running on the UI thread.
I want to show a progress bar while this operation is running.
The basic structure I have is below.
I want the timer event and update of the progress bar to happen on a
different thread or task while the long operation is running.
I should also mention that the long running operation also updates
other parts of the UI as it runs.
Can this be done?
private void btnStart_Click(object sender, EventArgs e)
{
StartProgressBar();
// start long running operation
StopProgressBar();
}
private void StartProgressBar()
{
tmrProgress.Enabled = true;
}
private void StopProgressBar()
{
tmrProgress.Enabled = false;
}
private void tmrProgress_Tick(object sender, EventArgs e)
{
if ((progressBar1.Value + 10) > progressBar1.Maximum)
{
progressBar1.Value = progressBar1.Minimum;
}
else
{
progressBar1.Value += 10;
}
}
I am not sure that I can follow you.

The UI updates must be done on the event thread.

You can start a separate thread for your long running task
and update the progress bar via Invoke.

Many years ago I wrote the following code:

byte[] b = new byte[1000];
int n;
while((n = f1.Read(b, 0, b.Length)) > 0 )
{
f2.Write(b, 0, n);
sofar += n;
if(bar.InvokeRequired)
{
bar.Invoke(new UpdateHandler(Update), new object[] {
sofar });
}
else
{
Update(sofar);
}
}
...
void Update(int n)
{
bar.Value = n;
}

I believe it can be done easier today, but still same concept.

Arne

Continue reading on narkive:
Loading...