我想从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


基础教程推荐
猜你喜欢
- WPF实现平面三角形3D运动效果 2023-03-09
- WPF实现动画效果(七)之演示图板 2023-06-21
- C#支付宝新版支付请求接口调用 2022-12-30
- WCF如何使用动态代理精简代码架构 2023-04-09
- C#使用async和await实现异步编程 2023-06-21
- C# 实现颜色的梯度渐变案例 2023-03-28
- WPF使用WrapPanel实现虚拟化效果 2023-07-04
- 使用mkbundle从C#源代码创建Linux可执行文件时出现问题 2023-09-19
- 解析C# 程序结构 2023-04-21
- 基于WPF实现一个简单的音频播放动画控件 2023-06-27