SqlConnection InfoMessage不使用BeginExecuteNonQuery

时间:2011-11-24 05:51:09

标签: c# sql-server ado.net

我想从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()
                        );    
        }

    }

1 个答案:

答案 0 :(得分:6)

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