2011-03-11 67 views
1

我想讀取MSMQ,其中隊列數據的字節數和排隊隊列數在1分鐘內產生的1500左右。所以如果連續讀取隊列cpu將繼續執行30%。並在一段時間後停止。我需要閱讀高達4小時的高容量隊列。 所以我想要安全線程閱讀的方式,不應該阻止。 其實我也不好對線程,因此你可以請幫我..想在c#中使用安全線程快速讀取msmq消息.net

目前我以這種方式正在讀

bool ProcessStatus; //process 
    Thread _UDPthreadConsme; 

    private void btn_receive_Click(object sender, EventArgs e) 
    { 

    if (MessageQueue.Exists(@".\private$\myquelocal")) 
    { 

    ThreadStart _processrcs = new ThreadStart(receivemessages); 
    _UDPthreadConsme = new Thread(_processrcs); 
    ProcessStatus = true; 
    _UDPthreadConsme.Start(); 
    } 
    } 


    private void receivemessages() 
    { 
    MessageBox.Show("Start"); 
    while (ProcessStatus) 
    { 
    try 
    { 

    // Connect to the a queue on the local computer. 
    MessageQueue myQueue = new MessageQueue(@".\private$\myquelocal"); 


    System.Messaging.Message[] myMessagecount = myQueue.GetAllMessages(); 

    if (myMessagecount.Length <= 0) 
    return; 


    myQueue.Formatter = new BinaryMessageFormatter(); 

    // Receive and format the message. 
    System.Messaging.Message myMessage = myQueue.Receive(); 
    byte[] buffer = (byte[])myMessage.Body; 

// here i convert buffer to its related structure and then insert the values in database sqlserver. 

} 
} 

回答

1

我會改寫這樣

private void receivemessages() 
    { 
     Console.WriteLine("Start"); 

     MessageQueue myQueue = new MessageQueue(@".\private$\myquelocal"); 

     while (ProcessStatus) 
     { 
      try 
      { 
       // Waits 100 millisec for a message to appear in queue 
       System.Messaging.Message msg = myQueue.Receive(new TimeSpan(0, 0, 0, 0, 100)); 

       // Take care of message and insert data into database 

      } 
      catch (MessageQueueException) 
      { 
       // Ignore the timeout exception and continue processing the queue 

      } 
     } 
    } 
+0

嗯。 halv klass? – jgauffin 2011-03-11 12:42:24

+0

忍者移動並意外擊中提交按鈕! ;-) – 2011-03-11 12:47:09

0

此代碼是一個在控制檯上運行並且異步讀取隊列的類的示例。這是最安全和最快速的方式。不過請注意,根據你在哪裏運行這個,你仍然需要有某種鎖定機制,如果你正在用消息體或類似的東西來更新文本框。

public sealed class ConsoleSurrogate { 

    MessageQueue _mq = null; 

    public override void Main(string[] args) { 

     _mq = new MessageQueue(@".\private$\my_queue", QueueAccessMode.Receive); 
     _mq.ReceiveCompleted += new ReceiveCompletedEventHandler(_mq_ReceiveCompleted); 
     _mq.Formatter = new ActiveXMessageFormatter(); 
     MessagePropertyFilter filter = new MessagePropertyFilter(); 
     filter.Label = true; 
     filter.Body = true; 
     filter.AppSpecific = true; 
     _mq.MessageReadPropertyFilter = filter; 
     this.DoReceive(); 

     Console.ReadLine(); 
     _mq.Close(); 
    } 

    void _mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { 
     _mq.EndReceive(e.AsyncResult); 
     Console.WriteLine(e.Message.Body); 
     this.DoReceive(); 
    } 

    private void DoReceive() { 
     _mq.BeginReceive(); 
    } 
}