C # Message Queue application-2

Source: Internet
Author: User
Tags export class

Inside this array, the CWorker class creates an implementation version of The CWorkerThread class.
. The CWorkerThread class (discussed below) is an abstract class that must be inherited. Export
Class defines the message processing method:
AThreads = new ArrayList ();
For (int idx = 0; idx <sfWorker. NumberThreads; idx ++)
{
WorkerThreadFormatter wfThread = new WorkerThreadFormatter ();
WfThread. ProcessName = sfWorker. ProcessName;
WfThread. ProcessDesc = sfWorker. ProcessDesc;
WfThread. ThreadNumber = idx;
WfThread. InputQueue = sfWorker. InputQueue;
WfThread. ErrorQueue = sfWorker. ErrorQueue;
WfThread. OutputName = sfWorker. OutputName;
// Define the auxiliary type and insert it into the auxiliary thread structure
CWorkerThread wtBase;
Switch (sfWorker. ProcessType)
{
Case WorkerFormatter. SFProcessType. ProcessRoundRobin:
WtBase = new CWorkerThreadRoundRobin (this, wfThread );
Break;
Case WorkerFormatter. SFProcessType. ProcessAppSpecific:
WtBase = new cworkerthreadappspecpacific (this, wfThread );
Break;
Case WorkerFormatter. SFProcessType. ProcessAssembly:
WtBase = new CWorkerThreadAssembly (this, wfThread );
Break;
Default:
Throw new Exception ("Unknown Processing Type ");
}
// Add a call to the array
AThreads. Insert (idx, wtBase );
}

Once all objects have been created, you can call the Start side of each thread object
To start them:
Foreach (CWorkerThread cThread in aThreads)
CThread. Start ();

The Stop, Pause, and Continue Methods perform similar operations in the foreach loop.
The Stop method has the following garbage collection operations:
GC. SuppressFinalize (this );

The Stop method will be called in the class destructor, so that the Stop party is not explicitly called.
In this case, the object can be terminated correctly. If the Stop method is called, no analysis is required.
Constructor. The SuppressFinalize method can prevent the Finalize method of the object from being called.
Implementation of the constructor ).

CWorkerThread abstract class

CWorkerThread is
The abstract classes inherited by RoundRobin and CWorkerThreadAssembly. No matter how it is processed
The majority of queue processing is the same, so the CWorkerThread class provides this function.
This class provides Abstract METHODS (must be replaced by actual methods) to manage resources and process messages.

Class is implemented again through the Start, Stop, Pause, and Continue methods.
The input and error queue are referenced in the Start method. In the. NET Framework, messages are sent by the System.
Messaging namespace processing:
// Try to open the queue and set the default read/write attribute
MessageQueue mqInput = new MessageQueue (sInputQueue );
MqInput. MessageReadPropertyFilter. Body = true;
MqInput. MessageReadPropertyFilter. AppSpecific = true;
MessageQueue mqError = new MessageQueue (sErrorQueue );
// If msmq com is used, set the formatting program to ActiveX.
MqInput. Formatter = new ActiveXMessageFormatter ();
MqError. Formatter = new ActiveXMessageFormatter ();

Once a Message Queue reference is defined, a thread is created for the actual processing function.
(ProcessMessages ). In the. NET Framework, use System. Threading
The namespace can easily implement thread processing:
ProcMessage = new Thread (new ThreadStart (ProcessMessages ));
ProcMessage. Start ();

The ProcessMessages function is a processing loop based on Boolean values. When the value is set
False. The processing cycle ends. Therefore, the Stop method of the thread object only sets this Boolean
Value, then close the open message queue, and add the thread with the main thread:
// Add the service thread and processing thread
BRun = false;
ProcMessage. Join ();
// Close the open Message Queue
MqInput. Close ();
MqError. Close ();

The Pause method only sets a Boolean value to sleep the processing thread for half a second:

If (bPause)
Thread. Sleep (500 );

Finally, each Start, Stop, Pause, and Continue method calls the abstract
OnStart, OnStop, OnPause, and OnContinue methods. These abstract methods are implemented
To capture and release the required resources.

The ProcessMessages loop has the following basic structure:
● Receive Message.
● If the Message has a successful Receive, the abstract ProcessMessage method is called.
● If Receive or ProcessMessage fails, send the Message to the error queue.

Message mInput;
Try
{
// Read from the queue and wait for 1 second
MInput = mqInput. Receive (new TimeSpan (0, 0, 1 ));
}
Catch (MessageQueueException mqe)
{
// Set the message to null
MInput = null;
// Check the error code to see if the error code times out.
If (mqe. ErrorCode! = (-1072824293) // 0xC00E001B
{
// If no timeout occurs, issue an error and record the error number
LogError ("Error:" + mqe. Message );
Throw mqe;
}
}
If (mInput! = Null)
{
// Obtain the message to be processed and call the abstract method for processing the message
Try
{
ProcessMessage (mInput );
}
// Catch known exceptions
Catch (CWorkerThreadException ex)
{
ProcessError (mInput, ex. Terminate );
}
// Capture unknown exceptions and call Terminate
Catch
{
ProcessError (mInput, true );
}
}

The ProcessError method sends an error message to the error queue. In addition, it may also lead
Terminate the thread by sending an exception. If the ProcessMessage method causes a termination error or CWorker
ThreadException type, which will perform this operation.

CworkerThread export class

Any class inherited from CWorkerThread must provide OnStart, OnStop, On
Pause, OnContinue, and ProcessMessage methods. OnStart and OnStop Methods
Obtain and release processing resources. OnPause and OnContinue methods allow temporary release and re-acquisition
Obtain these resources. The ProcessMessage method should process messages and reference them when a failure event occurs.
An exception occurred while sending CWorkerThreadException.

Since the CWorkerThread constructor defines runtime parameters, the export class must call the base class
Constructor:
Public CWorkerThreadDerived (CWorker v_cParent, WorkerThread
Formatter v_wfThread)
: Base (v_cParent, v_wfThread ){}

The export class provides two types of processing: sending messages to another queue or calling Group
Component method. The two methods of receiving and sending messages use the loop technology or application offset (
In the message AppSpecific attribute), as the deciding factor for which queue to use. This solution
The configuration file in should include a list of queue paths. OnStart and OnStop Methods
You should enable and disable references to these Queues:
IQueues = wfThread. OutputName. Length;
MqOutput = new MessageQueue [iQueues];
For (int idx = 0; idx <iQueues; idx ++)
{
MqOutput [idx] = new MessageQueue (wfThread. OutputName [idx]);
MqOutput [idx]. Formatter = new ActiveXMessageFormatter ();
}

In these solutions, message processing is simple: send messages to necessary output queues. In
In a loop, the process is:
Try
{
MqOutput [iNextQueue]. Send (v_mInput );
}
Catch (Exception ex)
{
// An error occurs when an error is forcibly terminated.
Throw new CWorkerThreadException (ex. Message, true );
}
// Calculate the next queue number
INextQueue ++;
INextQueue % = iQueues;

The latter method is interesting to call components with message parameters. ProcessMessage
Method call the IWebMessage interface to call a. NET component. OnStart and OnStop
To obtain and release the reference of this component.

The configuration file in this solution should contain two items: the complete class name and the file where the class is located
Location. Call the Process method on the component according to the definition in the IWebMessage interface.

To obtain the object reference, you must use the Activator. CreateInstance method. This letter
Number requires an assembly type. Here, it is exported from the Assembly file path and class name.
Once an object reference is obtained, it will be put into the appropriate interface:
Private IWebMessage iwmSample;
Private string sFilePath, sTypeName;
// Save the assembly path and type name
SFilePath = wfThread. OutputName [0];
STypeName = wfThread. OutputName [1];
// Obtain references to necessary objects
Assembly asmSample = Assembly. LoadFrom (sFilePath );
Type typSample = asmSample. GetType (sTypeName );
Object objSample = Activator. CreateInstance (typSample );
// Define necessary interfaces for objects
IwmSample = (IWebMessage) objSample;

After obtaining the object reference, the ProcessMessage method will be called on the IWebMessage interface.
Process Method:
WebMessageReturn wbrSample;
Try
{
// Define the parameters of a method call
String sLabel = v_mInput.Label;
String sBody = (string) v_mInput.Body;
Int iAppSpecific = v_mInput.AppSpecific;
// Call the method and capture the Returned Code
WbrSample = iwmSample. Process (sLabel, sBody, iAppSpecific );
}
Catch (InvalidCastException ex)
{
// If an error occurs in the message content, a non-termination exception is forcibly triggered.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.