Thursday, April 5, 2012

C# - UI freezes when calling background worker

Problem: When the user tries to update a data grid on main window in background workers progress changed method the UI freezes.

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
        DataTable oData = null; 
        SetDataSource(oData);
    }

    private void SetDataSource(object value) {
        dataGridView1.DataSource = value;
    }
 
An exception is thrown Cross thread operation.
 
 
 
 
Imapact: The user application crashes when populating data in grid view.
 
 
Solution: When calling the UI elements that were drawn on other thread than the 
calling thread a cross thread process exception is thrown.
 
We need to invoke the UI element to be drawn with the calling thread.
 
 
private delegate void SetDataSourceDelegate(object value);

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
        DataTable oData = null; 
        if (dataGridView1.InvokeRequired) {
            dataGridView1.Invoke(new SetDataSourceDelegate(SetDataSource), new Object[] {oData});
        }else{
            SetDataSource(oData); 
        }
    }

    private void SetDataSource(object value) {
        dataGridView1.DataSource = value;
    }
 

No comments:

Post a Comment