Question

I've been having difficulty getting my queries in C# to run asynchronously. I followed the example for BeginExecuteReader() on MSDN, but while the query is running, the program's window is frozen. I want to give some idea that the program is working and not frozen, which I thought is what the Begin/End methods let you do. I swapped out my huge query for a simpler one just for readability here.

private void mysqlHandler()
{
    statusLabel.Text = "Connecting to database...";
    string conStr = String.Format("Data Source=server;Initial Catalog=master; Integrated Security=SSPI");
    SqlConnection con = new SqlConnection(conStr);
    //go ahead and set these up
    string commandString = @"SELECT TOP 1 * FROM myTable";
    SqlCommand command = new SqlCommand(commandString, con);
    //try block for connecting to the database
    try
    {
        con.Open();
        statusLabel.Text = "Querying database";
        //try block for querying the database
        try
        {                    
            command.CommandType = CommandType.Text;
            IAsyncResult result = command.BeginExecuteReader();
            //let the user know stuff is happening
            while (!result.IsCompleted)
            {
                seconds++;
                int s = seconds % 60;
                int m = (int)Math.Floor((double)seconds / 60);
                queryTimerLabel.Text = String.Format("{0:D2}:{1:D2}", m, s);
                switch (seconds % 3)
                {
                    case 0:
                        statusLabel.Text = "Querying database.";
                        break;
                    case 1:
                        statusLabel.Text = "Querying database..";
                        break;
                    case 2:
                        statusLabel.Text = "Querying database...";
                        break;
                }
                System.Threading.Thread.Sleep(1000); //so while loop doesn't take up all the memory or something
            }
            SqlDataReader reader = command.EndExecuteReader(result); //get result
            seconds = 0; //reset time query has taken
            statusLabel.Text = "Query successful";
        }
        catch (Exception err)
        {
            showError(err);
            statusLabel.Text = "Error querying database";
        }
    }
    catch (Exception err)
    {
        showError(err);
        statusLabel.Text = "Error connecting to database";
    }
    finally
    {
        if (con != null)
            con.Close();
    }
}
Was it helpful?

Solution

You're in a while loop AND making your thread sleep for 1 second until it (the query) completes. You aren't doing anything asynchronously here.

You should probably look into ExecuteReaderAsync() instead if you can, because this loop you're doing is not going to make anything asynchronous.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top