John
John

Reputation: 727

Update label text before and after long running code

In my button listener, I have to do things.

1) Update the label text

StatusLabel.Text= "start";

2) process work, a little bit longer time.

3) Update the label text

StatusLabel.Text="end";

Why can I see "end" only?

I know the work should not run in UI thread, but how to do it in C#?

Upvotes: 0

Views: 1132

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156938

You have to do this asynchronous.

You can use something like this:

StatusLabel.Text= "start";

Task.Factory.StartNew( () => YourHeavyTask() ).ContinueWith( (n) => this.Invoke((MethodInvoker)delegate { StatusLabel.Text = "end"; }) );

This sample uses TPL, which is newer (and some people say better) then using BackgroundWorker, etc.

Personally I think both are good, depending on which you feel more comfortable with. I would suggest TPL when you have some more complex tasks depending on another or when they can run in parallel.

Upvotes: 2

Jacob
Jacob

Reputation: 78850

I assume you're running step #2 sequentially after 1 and before 3 within the same thread. The problem with this is that the code is never "yielding" control, so the application doesn't have a chance to draw the text change.

Use a BackgroundWorker or similar class in order to run step #2 in a separate thread to free up your UI thread.

Update:

I'd use a Task as Patrick suggests. If you do want to use BackgroundWorker, here's a sample of what you could do:

StatusLabel.Text = "start";

var worker = new BackgroundWorker();
worker.DoWork += (s, e) => YourHeavyTask();
worker.RunWorkerCompleted += (s, e) => StatusLabel.Text = "end";
worker.RunWorkerAsync();

Upvotes: 4

Related Questions