2016-11-09 54 views
2

我正在通過C#發送消息到服務代理隊列。我發送這樣的命令:C#發送消息到SQL Service Broker隊列

string send = String.Format("BEGIN TRANSACTION; BEGIN DIALOG {0} FROM SERVICE [/AVAILH/xml/InitService] TO SERVICE N'/AVAILH/xml/CreateFile' ON CONTRACT [/AVAILH/xml/Contract] WITH ENCRYPTION = OFF; SEND ON CONVERSATION {0} MESSAGE TYPE [/AVAILH/xml/CreateFile] ({1}); COMMIT TRANSACTION; GO", runID, xmlMessage); 

ThreadPool.QueueUserWorkItem(delegate 
{ 
    using (SqlConnection conn = new SqlConnection(connectionString)) 
    { 
    using(SqlCommand command = new SqlCommand(send, conn)) 
    { 
     conn.Open(); 
     command.ExecuteNonQuery(); 
    } 
    } 
}); 

但是,當這再次被調用,我得到一個錯誤。

類型 'System.Data.SqlClient.SqlException' 的未處理的異常出現在system.data.dll

其他信息:附近有語法錯誤 '2'。關鍵字附近

語法不正確「與」(....)

我只是試圖找出一個簡單的方法來發送消息到隊列,這將是反覆發生。

任何幫助或指導將非常感謝!

回答

2
var sendCmd = @" 
    BEGIN TRANSACTION; 

    DECLARE @cid UNIQUEIDENTIFIER; 
    DECLARE @xml XML = @message; 

/* Begin dialog the conversation id into this variable. */ 
    BEGIN DIALOG @cid FROM SERVICE [/AVAILH/xml/InitService] 
     TO SERVICE N'/AVAILH/xml/CreateFile' 
     ON CONTRACT [/AVAILH/xml/Contract] 
     WITH ENCRYPTION = OFF; 

    SEND ON CONVERSATION @cid 
     MESSAGE TYPE [/AVAILH/xml/CreateFile] (@xml); 

/* if you don't do this you will have converations open forever unless 
    you clean them up later */ 
    END CONVERSATION @cid; 

    COMMIT TRANSACTION; 
"; 

using(var conn = new SqlConnection(connectionString)) 
using(var command = new SqlCommand(sendCmd, conn)) 
{ 
    command.Parameters.AddWithValue("@message", xmlMessage); 
    conn.Open(); 
    command.ExecuteNonQuery(); 
} 

如果你想在同一個轉換髮送更多的信息,而不是END CONVERSATION @cid你可以這麼SELECT @cid和使用var cid = (Guid)command.ExecuteScalar();我也建議移動END CONVERSATION到內部激活,讀取器接收到結束或錯誤消息時並在您的閱讀器中通過END CONVERSATION確認上述消息的初始消息。