grmihel
grmihel

Reputation: 846

Run task asynchronously in C#

I have some process heavy tasks that run in my WinForms app. The problem is, while its running, it freeze the UI (UI main thread).

I haven't worked that much with threads and delegates in C# yet, and that's why I hope someone could help me to, how to handle those process heavy tasks, without freezing the UI, so the user don't think the app is crashing while waiting?

Eg. I have a call through my FrontController, that takes time:

_controller.testExportExcel(wrapper, saveDialog.FileName);

Since it's creating an Excel file. I won't the app to be responding on the UI while its working.

Another example of a process heavy task could be this:

private void dataGridView_liste_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
  if (e.ListChangedType != ListChangedType.ItemDeleted)
  {
     foreach (DataGridViewRow r in dataGridView_liste.Rows)
     {
       DataGridViewCellStyle red = dataGridView_liste.DefaultCellStyle.Clone();
       red.BackColor = Color.LightGreen;
       if (r.Cells["News"].Value != null && (bool)r.Cells["News"].Value == true)
         r.DefaultCellStyle = red;
     }
  }
}

Where the foreach loop takes time, and freeze the UI. An async thread running the process and automatically closing when its done, could be useful I think. But how does it work??

Upvotes: 0

Views: 11331

Answers (3)

tomfanning
tomfanning

Reputation: 9670

For your first example, a call to _controller.testExportExcel(), a BackgroundWorker or Task Parallel Library call (i.e. Task.Factory.StartNew(...)) would be appropriate to satify your requirement of keeping the UI responsive. Plenty of examples floating around, including the other answers here.

For your second example, you will find you can't put this on a background thread since it appears to be code that manipulates the UI. Specifically, if the implementation of your BackgroundWorker's DoWork event handler, or the delegate you pass to Task.Factory.StartNew(), or the method for a plain old thread touch the UI, you are highly likely (/certain?) to get an exception stating "Cross-thread operation not valid".

The reason for this is covered in this question. But I'm more surprised actually this is slow enough that you want to make it asynchronous. There might be some simple ways to make this code more responsive - Control.SuspendLayout() and .ResumeLayout() springs to mind.

Upvotes: 0

Jeb
Jeb

Reputation: 3799

How about using a Task (if targetting .net 4)? This is considered as a replacement of the BackgroundWorker class since it supports nesting (parent/child tasks), task continuations, etc.

E.g.

    private void dataGridView_liste_DataBindingComplete(object sender,
      DataGridViewBindingCompleteEventArgs e)  
    {
        Task t = Task.Factory.StartNew(() =>
        {
            // do your processing here - remember to call Invoke or BeginInvoke if
            // calling a UI object.
        });
        t.ContinueWith((Success) =>
        {
            // callback when task is complete.
        }, TaskContinuationOptions.NotOnFaulted);
        t.ContinueWith((Fail) =>
        {
            //log the exception i.e.: Fail.Exception.InnerException);
        }, TaskContinuationOptions.OnlyOnFaulted);

    }

Upvotes: 3

Louis Kottmann
Louis Kottmann

Reputation: 16648

I answered a very similar question here

It boils down to using BackgroundWorker.

msdn provides an example:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SL_BackgroundWorker_CS
{
    public partial class Page : UserControl
    {
        private BackgroundWorker bw = new BackgroundWorker();

        public Page()
        {
            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.tbProgress.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                this.tbProgress.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                this.tbProgress.Text = "Done!";
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}

Everything that runs in the DoWork event handler is asynchronous.
Everything that runs in ProgessChanged/RunWorkCompleted's event handlers is on the UI thread.

Upvotes: 2

Related Questions