Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Open thread in foreach loop
  2. foreach (System.Messaging.Message m in msgs)
  3. {
  4.     byte[] bytes = new byte[m.BodyStream.Length];
  5.     m.BodyStream.Read(bytes, 0, (int)m.BodyStream.Length);
  6.     System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
  7.  
  8.     ParserClass tst = new ParserClass(ascii.GetString(bytes, 0, (int)m.BodyStream.Length));
  9.     new Thread( new ThreadStart(tst.ProcessXML)).Start();
  10. }
  11.        
  12. private static object thLockMe = new object();
  13. public string xmlString { get; set; }
  14.  
  15. public ParserClass(string xmlStringObj)
  16. {
  17.     this.xmlString = xmlStringObj;
  18. }
  19.  
  20. public void ProcessXML()
  21. {
  22.     lock (thLockMe)
  23.     {
  24.         XDocument reader = XDocument.Parse(xmlString);
  25.         //Some more code...
  26.     }
  27. }
  28.        
  29. foreach (System.Messaging.Message m in msgs)
  30. {
  31.     byte[] bytes = new byte[m.BodyStream.Length];
  32.     m.BodyStream.Read(bytes, 0, (int)m.BodyStream.Length);
  33.     System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
  34.  
  35.     ParserClass tst = new ParserClass(ascii.GetString(bytes, 0, (int)m.BodyStream.Length));
  36.     ThreadPool.QueueUserWorkItem(x => tst.ProcessXML());
  37. }
  38.        
  39. private static object thLockMe = new object();
  40. public string XmlString { get; set; }
  41.  
  42. public ParserClass(string xmlString)
  43. {
  44.     XmlString = xmlString;
  45. }
  46.  
  47. public void ProcessXML()
  48. {
  49.     XDocument reader = XDocument.Parse(xmlString);
  50.     // some more code which doesn't need to access the shared resource
  51.  
  52.     lock (thLockMe)
  53.     {
  54.         // the necessary code to access the shared resource (and only that)
  55.     }
  56.  
  57.     // more code
  58. }