9.1. Filling a DataSet Asynchronously
Problem
Given some database queries that return large result sets and cause the calling application to be unresponsive, you need to make the application more responsive during the fill.
Solution
Create a background thread and use it to run a query to fill a
DataSet. You can also fill a
DataGrid object from a background thread.
The sample code contains one event handler and two methods:
- Go
Button.Click Checks whether there is an existing background thread loading the
DataSet. If theDataSetis not being loaded, a new thread is created invoking theAsyncFillDataSet( )method to fill aDataSet. Otherwise, a message is displayed stating that theDataSetis currently being filled.AsyncFillDataSet( )This method loads a
DataSetwith the Orders and Order Details tables from the Northwind database. TheBindDataSetToDataGrid( )method is called asynchronously on the form’s thread to display the results. Finally, messages are displayed to indicate that theAsyncFillDataSet( )method has started and when it has completed.BindDataSetToDataGrid( )This method binds the default view of the Orders table in the
DataSetto the data grid on the form.
The C# code is shown in Example 9-1.
Example 9-1. File: AsynchronousFillForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Threading; using System.Runtime.Remoting.Messaging; using System.Data; using System.Data.SqlClient; private delegate void BindDataSetToDataGridDelegate(DataSet ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access