9.2. Canceling an Asynchronous Query
Problem
Given a query running that runs asynchronously on a background thread, you want to give the user the option to cancel the query if it is taking too long.
Solution
Abort the background thread and clean up in an exception handler.
The sample code contains two event handlers and a single method:
- Start
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.- Cancel
Button.Click Aborts the background thread filling the
DataSet.AsyncFillDataSet( )This method loads a
DataSetwith the Orders and Order Details tables from the Northwind database. The method displays a message when the method has started and when it has completed. The method also traps theThreadAbortExceptionto handle the situation where the fill on the background thread is canceled.
The C# code is shown in Example 9-2.
Example 9-2. File: AsynchronousFillCancelForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Threading; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE = "OrderDetails"; // Relation name constants private const String ORDERS_ORDERDETAILS_RELATION = "Orders_OrderDetails_Relation"; ...
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