deXter
deXter

Reputation: 354

UI not responsive during frequent updates from background worker

I'm developing a windows form application that reads a file line by line[In background worker thread] and populates a datagridview[using BeginInvoke]. While this is being done the UI becomes non responsive(Unable to Cancel/Exit or drag window) but I'm able see datagridview being updated. What i know is that this is due to the fact that messages are being pumped into message queue which have higher priority than user input messages.

Is there a way by which the UI can still remain responsive to User Input?

Upvotes: 0

Views: 209

Answers (2)

Hitesh Pant
Hitesh Pant

Reputation: 1

Try to Use Task Library rather than going with BackgroundWorker(Task is anytime better than BackgroundWorker) , below snippet can help

    CancellationTokenSource tokenSource2 = new CancellationTokenSource();
    CancellationToken ct;
    public MainWindowViewModel()
    {      

        ct = tokenSource2.Token;
        Task.Factory.StartNew(PopulateDataGrid, ct);
    }

    /// <summary>
    /// 
    /// </summary>
    private void PopulateDataGrid()
    {           
        for (int i = 1; i < 10000; i++)
        {
            if (!ct.IsCancellationRequested)
            {

                 ///Populate Your Control here                   
            }
            else
            {
                break;
            }
        }
    }

    public void OnCancelCLick()
    {
        tokenSource2.Cancel();
    }
}

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31193

Since you are using BeginInvoke, you are doing things on the UI thread. If you read line by line and append each line one at a time, it doesn't really help having a background worker there.

You should rather add all at once, or at least in blocks, if there is some requirement to update the view while loading. Usually it's faster to just load and then add the data in one go.

Upvotes: 1

Related Questions