C# Function will work if i do not use async keyword

T.Zacks 3,986 Reputation points
2021-09-23T15:35:06.17+00:00

Please see this function body and tell me does it work as asynchronously or synchronously ? Thanks

private Task<bool> SaveData(string xml)
{
 bool status = false;
 try
 {
 using (var con = new SqlConnection(ConnectionString))
 using (var cmd = new SqlCommand("USP_CSMAddTabTickerAndClientWise", con))
 using (var da = new SqlDataAdapter(cmd))
 {
 con.Open();
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.Parameters.Add("@Xml", SqlDbType.Xml).Value = xml;
 status = (cmd.ExecuteNonQuery() > 0 ? true : false);
 }
 }
 catch (Exception ex)
 {
 status = false;
 MessageBox.Show("Error " + ex.Message);
 }

 return Task.FromResult(status);
}

string xml="sample data";
var task1 = SaveData(xml);
await Task.WhenAll(task1);
if ((bool)task1.Result)
{

}

EDIT

private async Task<bool> SaveData(string xml)
{
    bool status = false;
    try
    {
        using (var con = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand("USP_CSMAddTabTickerAndClientWise", con))
        using (var da = new SqlDataAdapter(cmd))
        {
            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@Xml", SqlDbType.Xml).Value = xml;
            status = ( await cmd.ExecuteNonQueryAsync() > 0 ? true : false);
        }
    }
    catch (Exception ex)
    {
        status = false;
        MessageBox.Show("Error " + ex.Message);
    }

    return status;
}

var task1 = SaveData(xml);
await Task.WhenAll(task1);
if ((bool)task1.Result)
{

}

Now i restructure my code. new structure code would be consider & working as asynchronously ? please guide me. thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,248 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-09-23T16:07:17.14+00:00

    You would be better off with this pattern which is asynchronous and needs no WhenAll, Call it without creating a new instance of the class then the result can be deconstructed from the named value tuple for success/failure and if the exception is not null show exception.Message.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Threading.Tasks;
    
    namespace Project1.Classes
    {
        public class DataOperations
        {
            private static  string ConnectionString = "TODO";
            public static async Task<(bool success, Exception exception)> SaveData(string xml)
            {
    
                try
                {
                    await using var con = new SqlConnection(ConnectionString);
                    await using var cmd = new SqlCommand("USP_CSMAddTabTickerAndClientWise", con);
                    using var da = new SqlDataAdapter(cmd);
                    await con.OpenAsync();
    
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@Xml", SqlDbType.Xml).Value = xml;
                    return ((await cmd.ExecuteNonQueryAsync() > 0), null);
                }
                catch (Exception ex)
                {
                    return (false, ex);
                }
            }
        }
    }
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2021-09-23T15:57:55.843+00:00

    It's a synchronous method that wraps it's result in a Task that's usually used to propagate asynchronous results.

    If you change your return type to bool and return this:

    return status;
    

    Instead of this:

    return Task.FromResult(status);
    

    Then the result will be the same. Then you can change the rest of your code to:

    string xml="sample data";        
    var result = SaveData(xml);
    if (result)
    {        
    
    }
    
    1 person found this answer helpful.