简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM