c# – SqlConnection InfoMessage不使用BeginExecuteNonQuery

我想从SQL存储过程中打印消息.如果我使用SYNC选项执行cmd.ExecuteNonQuery连接会触发InfoMessage事件,但是当我使用ASYNC选项执行时,不会触发该事件.在ASYNC执行时,我没有收到事件的原因吗?这是我的代码:class P...

我想从SQL存储过程中打印消息.

如果我使用SYNC选项执行cmd.ExecuteNonQuery连接会触发InfoMessage事件,但是当我使用ASYNC选项执行时,不会触发该事件.

在ASYNC执行时,我没有收到事件的原因吗?

这是我的代码:

 class Program
{
     static string connstring =
        "data source = xyz;initial catalog = abc;user id=abc;password=abc;Asynchronous Processing=True";
    static void Main(string[] args)
    {

        SqlConnection conn = new SqlConnection(connstring);

            conn.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);
            SqlCommand cmd = new SqlCommand("TMP_PROC", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TMP_ID", 1);

            try
            {
                Console.WriteLine("connection open");
                conn.Open();
                Console.WriteLine("executing query");
                //cmd.ExecuteNonQuery();
               var result= cmd.BeginExecuteNonQuery(
                    p =>
                    {
                        try
                        {
                            var asyncCommand = p.AsyncState as SqlCommand;
                            Console.WriteLine("Execution Completed");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error:::{0}", ex.Message);
                        }
                        finally
                        {
                            conn.Close();
                        }

                    }, cmd);
                int count = 0;
                while (!result.IsCompleted)
                {
                    Console.WriteLine("Waiting ({0})", count++);
                    // Wait for 1/10 second, so the counter
                    // does not consume all available resources 
                    // on the main thread.
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:::{0}" ,ex.Message);

            }
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

        Console.ReadLine();
    }

    static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
    {
        foreach (var error in e.Errors)
        {
            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine("Source {0} $Message{1} $error{2}", e.Source, e.Message,
                            error.ToString()
                        );    
        }

    }

解决方法:

非常简单;你必须在回调中调用EndExecuteNonQuery(result);这将触发事件.作为一般规则,您需要在IAsyncResult样式的Begin *方法上调用End *方法.一个值得注意的例外是Control.BeginInvoke,它明确地不需要这个.

本文标题为:c# – SqlConnection InfoMessage不使用BeginExecuteNonQuery

基础教程推荐