Why asynchronous code is so much slower than synchronous code

Viewed 352

I create a test table in SQL Server like this:

CREATE TABLE Person
(
    PersonID INT NOT NULL IDENTITY,
    PersonName NCHAR(500) NOT NULL,
    PersonFamily NCHAR(500) NOT NULL,
 
    CONSTRAINT PK_Person PRIMARY KEY(PersonID)
)

Then I create two methods to test async.

The first method uses an async approach to read all person, and the second one uses a sync approach.

Async method:

private async Task<List<Person>> ReadPersonsAsync()
{
    List<Person> result = new List<Person>();

    using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand())
        {
            sqlCommand.CommandText = "SELECT * FROM Person";
            sqlCommand.CommandType = System.Data.CommandType.Text;
            sqlCommand.Connection = sqlConnection;

            await sqlConnection.OpenAsync();

            using (var reader = await sqlCommand.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    result.Add(new Person
                    {
                        ID = int.Parse(reader[0].ToString()),
                        Name = reader[1].ToString(),
                        Family = reader[2].ToString()
                    });
                }
            }
        }
    }

    return result;
}

Sync method:

private List<Person> ReadPersons()
{
    List<Person> result = new List<Person>();

    using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand())
        {
            sqlCommand.CommandText = "SELECT * FROM Person";
            sqlCommand.CommandType = System.Data.CommandType.Text;
            sqlCommand.Connection = sqlConnection;

            sqlConnection.Open();

            using (var reader = sqlCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    result.Add(new Person
                    {
                        ID = int.Parse(reader[0].ToString()),
                        Name = reader[1].ToString(),
                        Family = reader[2].ToString()
                    });
                }
            }
        }
    }

    return result;
}

When I use the async approach it takes 10 seconds, but the sync approach is run in 2 seconds.

Which part of my code is wrong? Thanks.

1 Answers

The answer is that the async reader is simply less efficient than the "normal" reader in the version of Dot Net that you have.

sqlCommand.ExecuteReaderAsync()

is simply slower than

sqlCommand.ExecuteReader()

So for best performance you should read the data synchronously, or choose a different framework.

Related