MultiThreading with C1DataGrid for WPF

MultiThreading is mostly used to create more responsive user interface, although it can be used for other tasks as well, like performing some action while still waiting for a response from a web service. Suppose there is a C1DataGrid control bound to a datasource with 100,000 records and sorted, with styles implemented based on some criteria. When the grid has grouping and subtotals implemented and the datasource is constantly being updated in real time, all these operations need to be performed over and over again; and the grid needs to be updated as well. This situation with any grid component would result in an unresponsive UI. And, this is where we need the concept of multithreading. In this article, we create a basic WPF application using C1DataGrid and update its data using a BackgroundWorker. CRUD operations may be done on the UI thread as well. However, if there is too much of data updation/deletion, UI may freeze. Hence, we implement the same task in BackgroundWorker. Simply create a new instance of it, then call its RunWorkerAsync() method. This triggers the DoWork event. Here we perform the time consuming task(s) that may make the UI quite unresponsive. Here's some code:

//Create new BackGroundWorker  
var bgw = new System.ComponentModel.BackgroundWorker();  

//Start execution of a background operation.  

/*Occurs when RunWorkerAsync is called.  
Perform time-concuming task here */  
bgw.DoWork += (s, e) =>  
 for (int j = 0; j < 20; j++)  {   System.Threading.Thread.Sleep(500);   var \_fName = "FName" + (i).ToString();   var \_lName = "LName" + (i++).ToString();   var \_datum = \_fName + "," + \_lName;   AddNewRow(\_datum);  } }; //Background operation completed bgw.RunWorkerCompleted += (s, e) =>  
 // Back on UI thread  
 Console.WriteLine("Data Updated");  

We will use AddNewRow() function to add new data rows to the DataTable in the UI thread, keeping the last row selected and in view.

void AddNewRow(string _data)  
   new Action(() =>  
    // Add row on UI thread  
    //Select cell in last row and first column on UI thread  
    var _row = c1DataGrid1.Rows.Count - 1;  
    var _col = c1DataGrid1.Columns.Count - 1;  

    //Scroll the grid to the selected cell  
    c1DataGrid1.ScrollIntoView(\_row, \_col);  

Here is how the C1DataGrid with automatic data update, without freezing the UI, looks like: Download C# Sample Download Vb.Net Sample


GrapeCity Developer Tools
comments powered by Disqus