开发者

asynchronous function not executing sql CLR stored procedure

开发者 https://www.devze.com 2023-03-10 11:17 出处:网络
I have a CLR stored procedure that i want to execute asynchronously from C#. the code is as follow: private delegate void GeneratePayrollDelegate(string payProcessID);

I have a CLR stored procedure that i want to execute asynchronously from C#.

the code is as follow:

private delegate void GeneratePayrollDelegate(string payProcessID);

public void GeneratePayroll(string payProcessID)
    {
        GeneratePayrollDelegate del = new GeneratePayrollDelegate(GeneratePayrollAsync);
        del.BeginInvoke(payProcessID, null, null);
    }

public void GeneratePayrollAsync(string payProcessID)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(DLConnectionStringHelper.GetConnectionString() + "; async=true;"))
            {
                using (SqlCommand cmd = new SqlCommand("proc_GeneratePayroll", connection))
                {                        
                    cmd.CommandTimeout = 3600;
                    cmd.CommandType = CommandType.StoredProcedure;

                    connection.Open();
                    cm开发者_运维技巧d.ExecuteNonQuery();
                    connection.Close();
                }
            }
        }
        catch (Exception ex) { _Exceptions.ManageExceptions(ex); }
    }

This stored procedure executes successfully if it runs from sql.

When it executes from this code above, it gives no row inside the CLR stored procedure when trying to retrieve the row by the ID sent as parameter.

Need help!


you are calling cmd.ExecuteNonQuery(); you should call BeginExecuteReader instead to get result as sample code can be like this

private void Asynchronous(IAsyncResult asyncResult)
{
                System.Data.SqlClient.SqlDataReader reader;
                try
                {
                    System.Data.SqlClient.SqlCommand command =
                       asyncResult.AsyncState as System.Data.SqlClient.SqlCommand;
                    reader = command.EndExecuteReader(asyncResult);
                    while (reader.Read())
                    {

                    }
                    reader.Close();
                }
                catch
                {
                }
}

public void GeneratePayrollAsync(string payProcessID)
{
    try
    {
        using (SqlConnection connection = new SqlConnection("ConnectionString"))
        {
            using (SqlCommand command = new SqlCommand("proc_GeneratePayroll", connection))
            {
                command.CommandTimeout = 3600;
                command.CommandType = CommandType.StoredProcedure;
                //Set Your stored procedure parameter here
                connection.Open();
                command.BeginExecuteReader(Asynchronous, command, CommandBehavior.Default);

            }
        }
    }
    catch (Exception ex) {  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号