// Spludlow Software // Copyright © Samuel P. Ludlow 2020 All Rights Reserved // Distributed under the terms of the GNU General Public License version 3 // Distributed WITHOUT ANY WARRANTY; without implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE // https://www.spludlow.co.uk/LICENCE.TXT // The Spludlow logo is a registered trademark of Samuel P. Ludlow and may not be used without permission // v1.14 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Messaging; namespace Spludlow { public class QueueProcessor { public QueueProcessor() { } private System.Threading.EventWaitHandle WaitFinished = null; public void Stop() { if (WaitFinished != null) WaitFinished.Set(); } public void Run(string queueName) { WaitFinished = new EventWaitHandle(false, EventResetMode.ManualReset); string logName = "QueueProcessor-" + queueName; string queuePath = Spludlow.MessageQueues.Path(".", queueName); string text; using (LogFile logFile = new LogFile(logName + ".txt")) { try { using (MessageQueue queue = new MessageQueue(queuePath)) { BinaryMessageFormatter formatter = new BinaryMessageFormatter(); queue.Formatter = formatter; while (true) { IAsyncResult peekSyncResult = queue.BeginPeek(); int index = WaitHandle.WaitAny(new WaitHandle[] { WaitFinished, peekSyncResult.AsyncWaitHandle }); if (index == 0) { WaitFinished.Dispose(); break; } using (Message message = queue.EndPeek(peekSyncResult)) { peekSyncResult.AsyncWaitHandle.Dispose(); Spludlow.CallSet invokeInfo; try { invokeInfo = (Spludlow.CallSet)message.Body; } catch (Exception ee) { throw new ApplicationException("Casting Body, " + ee.Message, ee); } CallMethod methodInfo = invokeInfo.CurrentMethod; methodInfo.PickUpQueue = queueName; Spludlow.Call.Route(invokeInfo); queue.ReceiveById(message.Id); logFile.Append(logName + "\t" + methodInfo.Assembly + "\t" + methodInfo.Type + "\t" + methodInfo.Method + "\t"); } } } text = logName + "; Stopping when asked"; logFile.Append(text); Spludlow.Log.Warning(text); } catch (System.Threading.ThreadAbortException ee) { text = logName + "; Stopping with Thread Abort"; logFile.Append(text); logFile.Append(ee.ToString()); Spludlow.Log.Warning(text, ee); } catch (Exception ee) { text = logName + "; Error"; logFile.Append(text); logFile.Append(ee.ToString()); Spludlow.Log.Error(text, ee); throw ee; } } } } }