WCF 4 Step By Step Chapter13 Note (Implementing a WCF Service for Good Performance)

来源:互联网 发布:成男捏脸数据 编辑:程序博客网 时间:2024/05/16 14:19

Implementing a WCF Service for Good Performance

In this chapter, you will examine how to use servicethrottling to assist in maintaining scalability, how to encode data by using MTOM to reduce the overhead oftransmitting large binary data objects, and how to enable streaming to make best useof network bandwidth

Using Service Throttling to Control Resource Use 

when a message received by a service host reaches the top ofthe channel stack, it passes to a ChannelDispatcher object,which in turn passes it to the appropriate

EndpointDispatcher object, which invokes the correspondingmethod in the appropriate service instance. However,before forwarding the request to the EndpointDispatcher object, theChannelDispatcherobject can examine the currentload on the service and elect to delay the request if it would cause the service to exceedthe permissible load.In that case, the request is blocked and held in an internal queue untilthe load on the service eases. The ChannelDispatcher object has a propertycalledServiceThrottlethat you can use to help control how the ChannelDispatcher decides whether to block and queuerequests or let them execute.

            -MaxConcurrentInstances

            -MaxConcurrentCalls

            -MaxConcurrentSessions           

Configuring Service Throttling

In WCF 4.0, the default values are determined based on the available resources of the host computer. For example on a machine with a single-core processor, the default value for the maximum number of concurrent instances is 116, the default value for the maximum number of concurrent calls is 16, and the default value for the maximum number of concurrent sessions is 100 (the values you saw displayed in the Service Configuration Editor). On a dual-core machine, you will find that the defaults aredoubled Additionally, there is a relationship between the default values such that MaxConcurrentInstances = MaxConcurrentCalls +MaxConcurrentSessions

 

WCF and Service Instance Pooling

Creating and destroying instances are expensive, potentiallytime-consuming tasks. Service instance pooling would be very useful in this scenario. WCFdoes not provide service instance pooling directly, but it is possible to extend WCF by defining your own custom behavior that implements pooling.WCFsupplies theIInstanceProvider interface in the System.ServiceModel.Dispatcher namespacethat you can use to define your own service instance dispatch mechanism.

 

Specifying Memory Requirements

Applying a throttling behavior lets you limit the number of sessions and connections made to a service in an attempt to maintain throughput. However,services are simply applications that run on a computer, and if a service performsresource-intensive operations it may be better to ensure that sufficient resources are available before itstarts running. Onecommon resource that frequently runs short is memory.

You can indicate this value as them inFreeMemoryPercentageToActivate Service attribute of the<serviceHostingEnvironment>element in the service configuration file.

<configuration><system.ServiceModel><serviceHostingEnvironmentminFreeMemoryPercentageToActivateService="10" />...</system.ServiceModel></configuration>

In this case, if less than 10% of total memory is availablewhen the WCF runtime attempts to activate a service, it will fail with aServiceActivationException exception

 


Transmitting Data by Using MTOM

MTOMis an optimization mechanism for sending and receiving SOAP messages that contain binarydata.A SOAP message usually consists ofa message header that provides addressing, routing, and security information, anda message body, whichprovides the data, or payload, of the message.

A SOAP XML Message:

[ServiceContract]public interface IProductsService{...[OperationContract]bool ChangeStockLevel(string productNumber, int newStockLevel,string shelf, int bin);}

When a client application invokes the ChangeStockLeveloperation, the WCF runtime constructs

a message that looks like this:

<s:Envelopexmlns:a="http://www.w3.org/2005/08/addressing"xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Header>...</s:Header><s:Body><ChangeStockLevelxmlns="http://tempuri.org/"><productNumber>WB-H098</productNumber><newStockLevel>25000</newStockLevel><shelf>N/A</shelf><bin>40101</bin></ChangeStockLevel></s:Body></s:Envelope>

 

Remember that the XML message is transmitted as a series oftext characters when it traverses the network, andnon-text data, such asthe <newStockLevel> and the <bin> elements in the example above, must be converted to and froma text representation as the message is sent and received.

**Base64 encoding mechanism results in a string that isapproximately 140% of the length of the original data.

When you use MTOM to transmit a message that includes binary data, that data is not encoded as text,but is transmitted unchanged as an attachment to the messagethat follows the format of the well-known Multipurpose Internet Mail Extension (MIME)specification. Any text information in the original message is encoded as an XML infoset asbefore,but binary information is represented as a reference to the MIME attachment.

 

In WCF, MTOM is handled by a specific encoding channel. If you are using any of the standard HTTP bindings (basicHttpBinding, wsDualHttpBinding,wsFederationHttpBinding, or ws2007HttpBinding), you can change the MessageEncodingproperty of the binding configuration to MTOM to specify the MTOM encoding channel. Othertransports, such as TCP, MSMQ, and Named Pipes, use their own proprietary binaryencodings by default.

 

Transmitting message as text Sample:

 

Tannsmitting message as binary Sample:



Config MTOM


 

Controlling the Size of Messages

Apart from the MaxArrayLength property, the ReaderQuotaselement of all bindings provides several other properties: MaxBytesPerRead, MaxDepth,MaxNameTableCharCount, and Max StringContentLength. These properties determine thecomplexity of messages that the WCF runtime will process before throwing anexception. The data in the body of a message is an XML document;internally,  the WCF runtime usesanXmlDictionaryReader objectto parse the contents ofmessage bodies and break them up into theappropriate parameters, returning values that a service or client application expects. The WCF runtime uses the reader quota properties to configure the XmlDictionaryReader object and to constrain the messages it processes to a manageable size and structure.

The MaxBytesPerRead property specifies how many bytes the XmlDictionaryReader will read from the messageat one time while processing it; 

the MaxDepth property specifies the maximum node depthof elements in the message;

 the MaxNameTableCharCount property limits the total number ofcharacters in strings that are atomized in the NameTable for the XmlDictionaryReader; 

and the MaxStringContentLength determines the maximum length of string data that a messagecan contain. If you set any of these properties to zero, the XmlDictionaryReader will useits default settings.

The reader quota properties you are most likely to amendareMaxArrayLength and MaxStringContentLength, because these relate directly to the size ofthe data in the messages that you send.

 

However, this is not the end of the story. A message maycontain more than one array or string. The reader quota properties limit the size ofindividual elements but not the number of elements in a message, so it would still be possible tostage an effective Denial of Service attack. If you examine the General section for a bindingconfiguration in the Service Configuration Editor, you will see that a binding also has aMaxReceivedMessageSize property. This property governs the maximum overall size of a message thatcan be received.

 

you should always make sure that MaxReceivedMessageSize isat least as big as the greater of MaxArrayLength andMaxStringContentLength; if it is smaller, then

this limitation will kick in before the reader quotarestrictions are reached.

 

There is one other property that you should be aware of: MaxBufferSize. When a message is transmitted, it is sent as a stream of bytes over thenetwork. When a message is received, this stream must be reconstituted back into amessage. The WCF runtime uses an in-memory buffer to do this, and the maximum amount of memory it will allocate to this buffer is determined by the MaxBufferSizeproperty. In most cases, the value of Max BufferSize must be the same as MaxReceivedMessageSize (theWCF runtime will throw an exception if they are different when it attempts toreceive a message).

 

Streaming Data from a WCF Service

MTOM is useful for encoding large binary data objects in messages, but if these objects become too large, they can consume significant amounts ofmemory in the computer hosting the WCF service and the client applications that receivethem.Consider a WCF service that provides an operation that emits audio orvideo data. In this scenario, it is far more efficient to send andreceive the data as a stream than to try to transmit it as one big chunk.

Enabling Streaming in a WCF Service and Client Application WCF provides streaming support for operations by providingyou with a mechanism to modify theTransferMode property of bindingconfigurations based onthe basicHttpBinding, netTcpBinding, ornetNamedPipeBinding bindings.

TransferMode property

            -Buffered

            -StreamedRequest

            -StreamedResponse

            -Streamed

    

To support request streaming, an operation can take only a single input parameter, which must either be as tream object (a descendent of the System.IO.Stream class), a Message object (an instance ofthe System.ServiceModel.Channel. Message class or one of its descendants), or be serializableas XML.

To support response streaming, an operation must either have a non-void returntype or a single out parameterand, like the input parameter, the type of this return typeor parameter must either be a stream object or be serializable as XML. 

The reason for thisrestriction is that the input parameter (or output parameter or return type) must constitute the entire request or response message.  

e.g:

 

public interface IShoppingCartPhotoService{[OperationContract(Name = "GetPhoto")]Stream GetPhoto(string productNumber);}


 

原创粉丝点击