I would like to print messages from a SQL Stored Procedure.
If I execture with the SYNC option cmd.ExecuteNonQuery connection fires InfoMessage event, but when I execute with the ASYNC option, the event is not fired.
Is there a reason I am not receiving the events when executing 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()
);
}
}
Very simple; you must call EndExecuteNonQuery(result) in your callback; this will trigger the event. As a general rule, you are required to call the
End*method on anIAsyncResult-styleBegin*method. A notable exception isControl.BeginInvokewhich explicitly does not require this.