Mikeb
Mikeb

Reputation: 791

Async web service

Say I have a very simple web service:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SomeServices
{
    [OperationContract]
    [WebGet]
    public IEnumerable<int> GetSomeDatabaseNumbers()
    {
        return DB.GetMeSomeNumbers();
    }
}

The DBGetMeSomeNumbers method does some database retrieval.

I've been reading that the above will cause the request to block while we're waiting for the database to retrieve the data so I'm looking to use the new async features in .net 4.5 to get rid of this blocking issue and handle more requests while we're waiting for the database to get back. I've rewritten by database call like so:

public class DB {
    public static async Task<int[]> GetMeSomeNumbers()
    {
        List<int> rtnEntities = new List<int>();
        using (MySqlConnection sqlConn = new MySqlConnection(Settings.ConnectionString))
        {
            MySqlCommand sqlCmd = new MySqlCommand("SELECT number from SomeTable", sqlConn);
            sqlConn.Open();
            using (MySqlDataReader sqlRdr = await sqlCmd.ExecuteReaderAsync())
            {
                while (sqlRdr.Read())
                {
                    rtnEntities.Add(sqlRdr.GetInt32(0));
                }
                sqlRdr.Close();
            }
            sqlConn.Close();
        }
        return rtnEntities.ToArray();
    }
}

How do I modify my Web service call to use this new Async method?

Upvotes: 0

Views: 148

Answers (1)

Yurii
Yurii

Reputation: 4911

You can rewrite it this way:

public async Task<IEnumerable<int>> GetSomeDatabaseNumbers()
{
    return await DB.GetMeSomeNumbers();
}

Furthermore, I can't see any usages of generic type parameter in GetMeSomeNumbers<T>, so I assume you can remove it.

Upvotes: 2

Related Questions