How to query a database in .NET asynchronously.

I tried to execute the request asynchronously in .NET so that I could read the first few lines while the others were still being passed, but I had no luck so far.

The reason why I want to is because we often have to retrieve large tables from the database, and although you can not completely freeze the user interface using asnyc options ExecuteReader(), it seems that it is impossible to get data by row so that the user can see progress and possibly even work with the first piece of data.

I tried the following query:

SELECT 'Hello '
WAITFOR DELAY '0:0:10'
SELECT 'World!'

When I run this request with SqlCommand.BeginExecuteReader(callback), the callback function is called after about 10 seconds, so it clearly waits for the entire request to complete. I also tried SqlCommand.ExecuteReaderAsync()with the same results.

My question is this: is this possible in .NET? Or does this not work because of my query and will work better if verified using a real query (i.e. a large table)?

+4
source share
2 answers

Get the first 10 rows in the table.

SELECT TOP 10 * FROM table ORDER BY ID DESC

Then run the second query.

SELECT * FROM table ORDER BY ID DESC

Check if the first 10 have changed (Create, Update, Delete)

Update: Alternatively adding TOP and then using OFFSET, for example

SELECT TOP 10 * FROM table 

then

SELECT * FROM table OFFSET 10 LIMIT 50 

or pre SQL Server 2012 see Dave Ballantyne solution

+2
source

Not sure if you want to use in a web application or in windows

If the web, you can try this

  • , , 10

, .

0

All Articles