DooDoo
DooDoo

Reputation: 13487

Long running process freezing UI, how to update with threading?

I've written this sample code for a long running process, but the Windows Form freezes until the process completes. How do I change the code so that the work runs in parallel?

var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task t = Task.Factory.StartNew(delegate
{
    textBox1.Text = "Enter Thread";
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    textBox1.Text = textBox1.Text + Environment.NewLine + "After Loop";
}, CancellationToken.None, TaskCreationOptions.None, ui);

Upvotes: 1

Views: 5102

Answers (1)

Ohad Schneider
Ohad Schneider

Reputation: 38152

You can use a continuation. I don't remember the exact syntax but it's something like:

textBox1.Text = "Enter Thread"; //assuming here we're on the UI thread
Task t = Task.Factory.StartNew(delegate
{                
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    return result;
})
.ContinueWith(ret => textBox1.Text = textBox1.Text + Environment.NewLine + result, 
    TaskScheduler.FromCurrentSynchronizationContext());

An alternative would be something like:

Task t = Task.Factory.StartNew(delegate
{
    YourForm.Invoke((Action)(() => textBox1.Text = "Enter Thread");
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    YourForm.Invoke((Action)(() => textBox1.Text = textBox1.Text + Environment.NewLine + result);}, 
        CancellationToken.None, TaskCreationOptions.None);

Again, I don't remember the exact syntax but the idea is that you want to perform the long operation on a thread different than the UI thread, but report progress (including completion) on the UI thread.

By the way, the BackGroundWorker class would work very well here, too (I personally like it very much).

Upvotes: 6

Related Questions