Q:

Color datagridview rows without freezing C#

I have a datagridview with 5000 entries. And I want to color the rows based on some values. Here's how I do it:
    foreach (DataGridViewRow row in rows)
    {
        var handlingStage = (ESourceHandlingStage)row.Cells["HandlingStage"].Value;
        switch (handlingStage)
        {
            case ESourceHandlingStage.NotStarted:
                row.DefaultCellStyle.BackColor = UnhandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Given:
                row.DefaultCellStyle.BackColor = GivenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Taken:
                row.DefaultCellStyle.BackColor = TakenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Handled:
                row.DefaultCellStyle.BackColor = HandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Loaded:
                row.DefaultCellStyle.BackColor = LoadedColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            default:
                break;
        }
    }

But when form loads it freezes for a couple of seconds. Can can I avoid it?
Thank you for your help!

A:

You're looping though all the rows so this will take some time, the more rows you have the more time it will take.
You could put this processing onto a background thread, but you will need to marshal the code so that the actual change occurs on the UI thread. This would take the same amount of time, but wouldn't lock the UI while it processed.
An alternative would be to change the colour as each row is added. However, that does depend on your data being added one row at a time.

