SqlConnection InfoMessage not working with BeginExecuteNonQuery

I would like to print messages from an SQL stored procedure.

If I execture with the SYNC parameter cmd.ExecuteNonQuery the connection raises the InfoMessage event, but when I execute with the ASYNC option, the event does not fire.

Is there a reason I don't get events when executed in ASYNC?

Here is my code:

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() ); } } 
+4
source share
1 answer

Very simple; You must call EndExecuteNonQuery (the result) in your callback; this will trigger an event. Usually you need to call the End* method IAsyncResult IAsyncResult -style Begin* method. A notable exception is Control.BeginInvoke , which does not explicitly require this.

+6
source

Source: https://habr.com/ru/post/1382829/


All Articles