![](/img/trans.png)
[英]Saving SqlConnection.InfoMessage to string in Entity Framework 6
[英]SqlConnection InfoMessage not working with BeginExecuteNonQuery
我想從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*
Begin*
方法。 一個值得注意的例外是Control.BeginInvoke
,它明確地不需要這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.