petshop以异步方式插入订单的疑惑(后面理解了)

PetShop.OrderProcessor是一个控制台应用程序,我很奇怪这个控制台程序是怎样在web应用程序中的。不管怎样,老习惯先分析下这个控制台程序吧:

1 staticvoid Main() {
2
3 Thread workTicketThread;
4 Thread[] workerThreads =new Thread[threadCount];
5
6 for (int i =0; i < threadCount; i++) {
7
8 workTicketThread =new Thread(new ThreadStart(ProcessOrders));
9
10 // Make this a background thread, so it will terminate when the main thread/process is de-activated
11   workTicketThread.IsBackground =true;//该值指示某个线程是否为后台线程。
12   workTicketThread.SetApartmentState(ApartmentState.STA);
13
14 // Start the Work
15   workTicketThread.Start();
16 workerThreads[i] = workTicketThread;
17 }

不难看出这是一个多线程的程序。在这里多线程到底是怎样工作的呢?这个是个疑惑。

接下来看看这个线程数组执行的函数ProcessOrders,还是先给出这个函数的代码吧:

1 privatestaticvoid ProcessOrders() {
2
3 // 定义了事务的超时时间
4   TimeSpan tsTimeout = TimeSpan.FromSeconds(Convert.ToDouble(transactionTimeout * batchSize));//30*10
5 //BLL层的order
6   Order order =new Order();
7 while (true) {
8
9 //队列超时变量
10   TimeSpan datetimeStarting =new TimeSpan(DateTime.Now.Ticks);
11 double elapsedTime =0;
12
13 int processedItems =0;
14
15 ArrayList queueOrders =new ArrayList();
16
17 //OrderInfo orderData = orderQueue.Receive(timeout);
18  using (TransactionScope ts =new TransactionScope(TransactionScopeOption.Required, tsTimeout)) {
19 // Receive the orders from the queue
20  for (int j =0; j < batchSize; j++) {
21
22 try {
23 //only receive more queued orders if there is enough time
24  if ((elapsedTime + queueTimeout + transactionTimeout) < tsTimeout.TotalSeconds) {
25 queueOrders.Add(order.ReceiveFromQueue(queueTimeout));//从BLL.Order.ReceiveFromQueue得到订单队列,并将其放入到ArrayList中
26   }
27 else {
28 j = batchSize; // exit loop
29   }
30
31 //update elapsed time
32   elapsedTime =new TimeSpan(DateTime.Now.Ticks).TotalSeconds - datetimeStarting.TotalSeconds;
33 }
34 catch (TimeoutException) {
35
36 //exit loop because no more messages are waiting
37   j = batchSize;
38 }
39 }
40
41 //process the queued orders
42  for (int k =0; k < queueOrders.Count; k++) {
43 order.Insert((OrderInfo)queueOrders[k]);//再调用BLL.Order.Insert方法吧得到的订单插入到Order和Invertory中
44   processedItems++;
45 totalOrdersProcessed++;
46 }
47
48 //batch complete or MSMQ receive timed out
49   ts.Complete();
50 }
51
52 Console.WriteLine("(Thread Id "+ Thread.CurrentThread.ManagedThreadId +") batch finished, "+ processedItems +" items, in "+ elapsedTime.ToString() +" seconds.");
53 }
54 }

最重要的部分应该是行25和43吧,先是从BLL.Order.ReceiveFromQueue得到订单队列,并将其放入到ArrayList中,

然后就是再调用BLL.Order.Insert方法吧得到的订单插入到Order和Invertory中。这是我的理解,但是我看了好久还是没有看到他们是怎么把

从消息队列中获取的order数据插入到数据库Order表和Invertory表中。

我之前为什么会有这样的困惑(消息队列的消息怎么插入到数据库),后面我知道了,我认真的读了下BLL.Order发现,BLL.Order的Insert方法插入数据的

方法并不是用异步的方法,如果他真的用异步的方法的话,而是直接插入到Order和Invertory中。故这个困惑解决了。

原文地址:https://www.cnblogs.com/huaizuo/p/2102562.html