异步函数不执行sql CLR存储过程

时间:2011-06-06 09:21:44

标签: c# .net sql asynchronous sqlclr

我有一个CLR存储过程,我想从C#异步执行。

代码如下:

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();
                    cmd.ExecuteNonQuery();
                    connection.Close();
                }
            }
        }
        catch (Exception ex) { _Exceptions.ManageExceptions(ex); }
    }

如果从sql运行,则此存储过程将成功执行。

当从上面的代码执行时,在尝试通过作为参数发送的ID检索行时,它在CLR存储过程中不提供任何行。

需要帮助!

1 个答案:

答案 0 :(得分:1)

你打电话给cmd.ExecuteNonQuery();您应该调用BeginExecuteReader来获取结果,因为示例代码可以像这样

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) {  }
}