0

I have made a simple example that returns the data from a database table.

private Task<DataSet> GetDataAsync(string connStr)
    {
        return Task.Run(() =>
        {                
            DataSet ds = new DataSet();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE", conn))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
            return ds;
        });            
    }

What would have been the difference if a had marked the method as async and instead of return Task.Run I would have used return await Task.Run?

domyos500
  • 3
  • 1
  • 1
    You may also find this article interesting: [Should I expose asynchronous wrappers for synchronous methods?](https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/) – Theodor Zoulias Apr 21 '20 at 04:15

1 Answers1

1

The short answers are "yes" and "yes".

You can use Task.Run without await and async. Clearly. That's how your code is currently written and it works.

If you had marked the method as async you would have had to use return await Task.Run.

Now, in this case it's of no real value because you are just instantly returning the results of the Task.Run. Callers to your code can decide independently of your code if they use await or not on the result of your method.

The only time that it make a difference is if your code were using await throughout the method. For example, should there be a FillAsync method then this code would be valid:

private async Task<DataSet> GetData2Async(string connStr)
{
    DataSet ds = new DataSet();
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM TABLE", conn))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                await da.FillAsync(ds);
            }
        }
    }
    return ds;
}

Please note that await da.FillAsync(ds); is fictional for illustrative purposes.

In this code then you need async on your method to await the FillAsync.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172