gpt4 book ai didi

c# - SqlConnection InfoMessage 不适用于 BeginExecuteNonQuery

转载 作者:太空狗 更新时间:2023-10-30 00:56:12 31 4
gpt4 key购买 nike

我想打印来自 SQL 存储过程的消息。

如果我使用 SYNC 选项执行 cmd.ExecuteNonQuery 连接会触发 InfoMessage 事件,但是当我使用 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* 方法.一个值得注意的异常(exception)是 Control.BeginInvoke,它明确不需要这样做。

关于c# - SqlConnection InfoMessage 不适用于 BeginExecuteNonQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252734/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com