我正在编写的应用程序发送存储在数据库中的 SMS 消息。对于这一部分,我正在编写一个 Windows 服务,它将通过选择的数据库,然后将等待消息作为 HTTP 请求发送。
因为应用程序正在发送 SMS,所以速度很重要。现在,我每秒只收到大约 15 个请求。现在,应用程序创建SMSMessages
它们,然后将它们放入同步队列中。我使用多线程从该队列中一次运行 20 个线程。
我注意到如果我运行了太多线程,那么应用程序实际上会减慢每秒发送的消息数。
我想弄清楚是否有比我发送请求更快的方法。有没有更好的方法来组织我的线程,或者我应该使用线程池或异步请求来优化应用程序?
主要代码在这里:
Queue Messages = new Queue();
DataRow[] Rows = dtSMSCombined.Select(); //Created from a datatable
foreach (DataRow Row in Rows)
{
... //Get information from the row.
SMSMessage oSMS = new SMSMessage(Keyword, Number, Message, MessageID);
Messages.Enqueue(oSMS);
}
Queue SyncedMessages = Queue.Synchronized(Messages);
var tasks = new Task[20];
for (int i = 0; i < 20; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{ //each thread will pull out new items from the queue as they finish
while (SyncedMessages.Count > 0)
{
Response = new XDocument();
SMSMessage oSMS = (SMSMessage)SyncedMessages.Dequeue();
if (oSMS.GetMessage() != null && oSMS.GetMessage() != string.Empty)
{
Response = oSMS.SendSMS();
}
string ResponseCode = (string)Response.Descendants("response").First();
if (ResponseCode == "ok")
{
oSMS.sResponseCode = ResponseCode;
oSMS.dCompleted = DateTime.Now;
}
else { }
oSMS.DTInsert();
}
});
}
while (tasks.Any(t => !t.IsCompleted)) { }
这是类中的SendSMS()
方法SMSMessage
:
public XDocument SendSMS()
{
XML = "<message id=\""+ lMessageID +"\"><partnerpassword>" + PartnerPassword + "</partnerpassword><content>" + sMessage + "</content></message>";
URL = "http://sloocetech.net:****/spi-war/spi/" + PartnerID + "/" + sRecipient + "/" + Keyword + "/messages/mt";
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Proxy = null;
RequestBytes = System.Text.Encoding.ASCII.GetBytes(XML);
Request.Method = "POST";
Request.ContentType = "text/xml;charset=utf-8";
Request.ContentLength = RequestBytes.Length;
RequestStream = Request.GetRequestStream();
RequestStream.Write(RequestBytes, 0, RequestBytes.Length);
RequestStream.Close();
HttpWebResponse Resp = (HttpWebResponse)Request.GetResponse();
oReader = new StreamReader(Resp.GetResponseStream(), System.Text.Encoding.Default);
string backstr = oReader.ReadToEnd();
oReader.Close();
Resp.Close();
Doc = XDocument.Parse(backstr);
return Doc;
}