1

i am currently working on an Web api project where we are using repository pattern but unfortunately we do not use EF.

So for the data access layer we use ADO.NET in which we call the stored procedures on the database. Bad architecture i know.

Anyway the problem i recently discovered (due to the fact i was working on the other layers) is that even if all the layers are implemented by using tasks and the data access layer is not and if i am not mistaken if in a chain of asynchronous method calls there is an synchronous method call that turns the whole process into synchronous.

So initially i had methods like this one:

  public DataTable GetClients()
  {
    using (var conn = new SqlConnection(CMS))
    {
        using (var cmd = new SqlCommand("[dbo].[ClientsReturn]"))
        {
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;

            conn.Open();
            var adapter = new SqlDataAdapter(cmd);

            var ds = new DataSet();
            adapter.Fill(ds);

            var T = ds.Tables[0];

            return T;
        }
    }
}

So after some search i change the method and generally the classes to something like

public async Task<DataTable> GetClients()
{
    var ds =  new DataSet();
    using (var conn = new SqlConnection(CMS))
    {
        using (var cmd = new SqlCommand("[dbo].[ClientsReturn]"))
        {
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            await conn.OpenAsync();  

            var adapter = new SqlDataAdapter(cmd);    
            await Task.Run(() => adapter.Fill(ds));

            var T = ds.Tables[0];
            return T;
        }
    }
}

Is this looking right to you?Any suggestions?

Thanks in advance.

user1859022
  • 2,585
  • 1
  • 21
  • 33
kostas.kapasakis
  • 920
  • 1
  • 11
  • 26
  • Have you tested this? Does it work for you? – Enigmativity Jul 10 '18 at 10:02
  • Yes it is working , meaning no run-time errors.I am just not sure if this implementation is the proper way to convert the previous synchronous method to asynchronous. – kostas.kapasakis Jul 10 '18 at 10:06
  • Looks good. I'd create and return `Table` in task what calls `Fill()` though, then you don't need second `await`, simply return that task. – Sinatr Jul 10 '18 at 10:16
  • @Sinatr - Isn't the second `await` necessary to hold the code from ending the `using` statements? – Enigmativity Jul 10 '18 at 10:26
  • @Enigmativity, it's [not needed](https://stackoverflow.com/q/16566547/1997232). Dispose will not occurs upon returning task, but at some point of executing that task (later). – Sinatr Jul 10 '18 at 10:29
  • Guys i see a massive slow down of the program , i have change some things like adding configureAwait(false) but that did not make any difference any ideas? – kostas.kapasakis Jul 11 '18 at 12:53

0 Answers0