- /// <summary>
- /// 扫描订单集合启动发送短信委托
- /// </summary>
- public void GsmStartSendMessage(object o)
- {
- try
- {
- SmartThreadPool stp = new SmartThreadPool();//这里演示了线程的分组
- //创建一个分组并用这个分组管理
- //如果需要设置这个分组为调用start的时候才开始运行,需要传入WIGStartInfo参数,将其参数中的StartSuspended设置为true然后调用分组的start方法
- IWorkItemsGroup mainGroup = stp.CreateWorkItemsGroup(30);
- mainGroup.OnIdle += mainGroup_OnIdle;
- while (true)
- {
- _areSendMsg.WaitOne();
- Thread.Sleep(1000);
- //扫描订单集合
- foreach (var keyValuePair in sendQueue)
- {
- KeyValuePair<GSMMONDEMABS, ConcurrentQueue<SMSServerModel>> pair = keyValuePair;
- if (pair.Value.Count == 0)
- {
- continue;
- }
- if (pair.Key.IsTakeUp)
- mainGroup.QueueWorkItem(new WorkItemCallback(ExecuteGsmSendMessage), pair);
- //ExecuteGsmSendMessage(pair);
- }
- //分组等待所有任务完成
- mainGroup.WaitForIdle();
- }
- }
- catch (Exception ex)
- {
- _log.Error(ex);
- DelegateValue("GsmStartSendMessage" + ex.Message);
- }
- }
复制代码
- /// <summary>
- /// 发送短信委托
- /// </summary>
- /// <param name="queue"></param>
- /// <param name="gsm"></param>
- public object ExecuteGsmSendMessage(object o)
- {
- ConcurrentQueue<SMSServerModel> queue = ((KeyValuePair<GSMMONDEMABS, ConcurrentQueue<SMSServerModel>>)o).Value;
- GSMMONDEMABS gsm = ((KeyValuePair<GSMMONDEMABS, ConcurrentQueue<SMSServerModel>>)o).Key;
- try
- {
- ConcurrentQueue<SMSServerModel> tempQueue = queue;
- while (tempQueue.Count > 0)
- {
- Thread.Sleep(4000);
- string comName = string.Empty;
- string phone = string.Empty;
- try
- {
- SMSServerModel obj = null;
- if (tempQueue.TryDequeue(out obj))
- {
- if (!gsm.IsTakeUp)
- {
- continue;
- }
- if (!gsm.IsOpen)
- {
- gsm.Open();
- }
- comName = gsm.ComPort;
- obj.COMNO = gsm.ComPort;
- phone = obj.PREPAID_PHONE_NO;
- var msgText = gsm.ComModel.Pwd + "," + obj.PREPAID_PHONE_NO + "," + obj.MONEY;
- //充值短信格式:密码,手机号,金额
- gsm.SendMsg("10086500", msgText);
- bool bl = Bll.SendMsgUpdateByOrder(DateTime.Now.ToString(), "1", msgText, obj.ORDERNO,
- gsm.ComModel.PhoneNumber, obj.COMNO);
- alreadySendList.Add(obj);
- DelegateValue(obj.COMNO + ": " + msgText + " (" + obj.BELONGINGTO + ")发送成功,ThreadId:" +
- Thread.CurrentThread.ManagedThreadId + " (更新数据" + (bl ? "成功)" : "失败)"));
- this.Invoke(new Action(delegate
- {
- this.lblsum.Text = "当前订单数:" + sendQueue.Sum(q => q.Value.Count);
- }));
- }
- }
- catch (Exception ex)
- {
- DelegateValue(comName + " 发送短信异常:" + phone + ex);
- }
- finally
- {
- //if (!sendQueue.Any(q => q.Value.Count > 0))
- //{
- // _areReaddb.Set(); //通知读取数据库
- // _areSendMsg.Reset(); //停止发送短信线程
- //}
- }
- }
- }
- catch (Exception ex)
- {
- DelegateValue("ExecuteGsmSendMessage" + ex);
- _log.Error(ex);
- }
- return 0;
- }
复制代码
- void mainGroup_OnIdle(IWorkItemsGroup workItemsGroup)
- {
- if (!sendQueue.Any(q => q.Value.Count > 0))
- {
- _areReaddb.Set(); //通知读取数据库
- _areSendMsg.Reset(); //停止发送短信线程
- }
- }
复制代码
还有怎么优化,可以支持多线程发送。一个端口起一个线程,并行发送 |