How do I process the SqlCommand result (strings) as they come in?

How do I process the SqlCommand result (rows) as they come in? In other words, I am trying to do exactly what Sql Management Studio 2005 does when executing a query with many thousands of rows. To me it looks like, once Sql has found the first result, it notifies the UI and displays the rows as they come up.

I assume it can be done asynchronously with BeginExecuteReader and EndExecuteReader, however (in my tests) the callback method is only called when the result set is complete. Any idea on how to replicate Sql Management Studio 2005?

Thank!

+2


source to share


2 answers


Don't do an async operation, just call ExecuteReader

and then iterate over the result set as it comes in.

using(SqlCommand cmd = new SqlCommand(......))
using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while(rdr.Read())
    {
        // read and interpret row
        // possibly update GUI or something
    } 
}

      



If you need to update any interface or something while processing it, you can always call another method with a new line read.

Mark

+6


source


For your application to remain responsive, your main GUI thread must be able to handle incoming messages. This is even true for drawing on the screen; you can update the shortcut text, but it will not appear on the screen until the Update Shortcut window message has been processed.

The lightweight way of reacting often calls Application.DoEvents (). This will basically process all incoming messages and return.



If you have individual operations that take a long time, such as ExecuteReader (), you may not be able to call DoEvents () fast enough. In this case, you must return to the background thread. One of the relatively simple ways to use a background thread is the BackgroundWorker component. There's a good example in this blog post .

+1


source







All Articles