concept memory consumption in category .net

This is an excerpt from Manning's book Concurrency in .NET.
Lazy initialization is another variation of caching. Specifically, this technique defers the computation of a factory function for the instantiation of an object until needed, creating the object only once. The main purpose of lazy initialization is to improve performance by reducing memory consumption and avoiding unnecessary computation.
Listing 12.9 Parallel stream compression and encryption using TDF
async Task CompressAndEncrypt( Stream streamSource, Stream streamDestination, long chunkSize = 1048576, CancellationTokenSource cts = null) { cts = cts ?? new CancellationTokenSource(); #1 var compressorOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, BoundedCapacity = 20, #2 CancellationToken = cts.Token }; var inputBuffer = new BufferBlock<CompressingDetails>( new DataflowBlockOptions { CancellationToken = cts.Token, BoundedCapacity = 20 }); #2 var compressor = new TransformBlock<CompressingDetails, CompressedDetails>(async details => { var compressedData = await IOUtils.Compress(details.Bytes); #3 return details.ToCompressedDetails(compressedData); #4 }, compressorOptions); var encryptor = new TransformBlock<CompressedDetails, EncryptDetails>( async details => { byte[] data = IOUtils.CombineByteArrays(details.CompressedDataSize, ➥ details.ChunkSize, details.Bytes); #5 var encryptedData = await IOUtils.Encrypt(data); #6 return details.ToEncryptDetails(encryptedData); #4 }, compressorOptions); var asOrderedAgent = Agent.Start((new Dictionary<int, EncryptDetails>(),0), async((Dictionary<int,EncryptDetails>,int)state,EncryptDetails msg)=>{ #7 Dictionary<int, EncryptDetails> details, int lastIndexProc) = state; details.Add(msg.Sequence, msg); while (details.ContainsKey(lastIndexProc+1)) { msg = details[lastIndexProc + 1]; await streamDestination.WriteAsync(msg.EncryptedDataSize, 0, msg.EncryptedDataSize.Length); await streamDestination.WriteAsync(msg.Bytes, 0, msg.Bytes.Length); #8 lastIndexProc = msg.Sequence; details.Remove(lastIndexProc); #9 } return (details, lastIndexProc); }, cts); var writer = new ActionBlock<EncryptDetails>(async details => await asOrderedAgent.Send(details), compressorOptions); #12 var linkOptions = new DataflowLinkOptions { PropagateCompletion = true }; inputBuffer.LinkTo(compressor, linkOptions); #13 compressor.LinkTo(encryptor, linkOptions); #13 encryptor.LinkTo(writer, linkOptions); #13 long sourceLength = streamSource.Length; byte[] size = BitConverter.GetBytes(sourceLength); await streamDestination.WriteAsync(size, 0, size.Length); #14 chunkSize = Math.Min(chunkSize, sourceLength); #15 int indexSequence = 0; while (sourceLength > 0) { byte[] data = new byte[chunkSize]; int readCount = await streamSource.ReadAsync(data, 0, data.Length); #16 byte[] bytes = new byte[readCount]; Buffer.BlockCopy(data, 0, bytes, 0, readCount); var compressingDetails = new CompressingDetails { Bytes = bytes, ChunkSize = BitConverter.GetBytes(readCount), Sequence = ++indexSequence }; await inputBuffer.SendAsync(compressingDetails); #17 sourceLength -= readCount; #18 if (sourceLength < chunkSize) chunkSize = sourceLength; #18 if (sourceLength == 0) inputBuffer.Complete(); #19 } await inputBuffer.Completion.ContinueWith(task => compressor.Complete()); await compressor.Completion.ContinueWith(task => encryptor.Complete()); await encryptor.Completion.ContinueWith(task => writer.Complete()); await writer.Completion; await streamDestination.FlushAsync(); } #1 A new cancellation token is provided if none is supplied in the constructor. #2 Sets the BoundedCapacity value to throttle the messages and reduce memory consumption by limiting the number of MemoryStreams created at the same time #3 Asynchronously compresses the data (the method is provided in the source code of the book) #4 Converts the current data structure into the message shape to send to the next block #5 Combines the data and metadata into a byte array pattern that will be deconstructed and parsed during the revert operation decrypt–decompress #6 Asynchronously encrypts the data (the method is provided in the source code of the book) #7 The behavior of the asOrderedAgent Agent keeps track of the order of the messages received to maintain the order (persist the data). #8 Persists the data asynchronously; the file stream could be replaced with a network stream to send the data across the wire. #9 The chunk of data that is processed is removed from the local state, keeping track of the items to perform. #12 The ActionBlock reader sends the chunk of data wrapped into a details data structure to the asOrdered agent. #13 Links the dataflow blocks to compose the workflow #14 The total size of the file stream is persisted as the first chunk of data; in this way, the decompression algorithm knows how to retrieve the information and how long to run. #15 Determines the chunk size to partition data #16 Reads the source stream into chunks until the end of the stream #17 Sends the chunk of data read from the source stream to the inputBuffer #18 Checks the current source stream position after each read operation to decide when to complete the operation #19 Notifies the input buffer when the source stream reaches the end !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":7,\"ch\":1},{\"line\":7,\"ch\":23}],[{\"line\":8,\"ch\":1},{\"line\":8,\"ch\":16}],[{\"line\":14,\"ch\":32},{\"line\":14,\"ch\":47}],[{\"line\":86,\"ch\":13},{\"line\":86,\"ch\":28}],[{\"line\":12,\"ch\":22},{\"line\":12,\"ch\":33}],[{\"line\":8,\"ch\":1},{\"line\":8,\"ch\":16}],[{\"line\":14,\"ch\":32},{\"line\":14,\"ch\":47}],[{\"line\":86,\"ch\":13},{\"line\":86,\"ch\":28}],[{\"line\":16,\"ch\":21},{\"line\":16,\"ch\":35}],[{\"line\":22,\"ch\":20},{\"line\":22,\"ch\":34}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":5}],[{\"line\":17,\"ch\":24},{\"line\":17,\"ch\":29}],[{\"line\":23,\"ch\":1},{\"line\":23,\"ch\":6}],[{\"line\":32,\"ch\":1},{\"line\":32,\"ch\":6}],[{\"line\":47,\"ch\":45},{\"line\":47,\"ch\":50}],[{\"line\":92,\"ch\":22},{\"line\":92,\"ch\":27}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":16,\"ch\":21},{\"line\":16,\"ch\":35}],[{\"line\":22,\"ch\":20},{\"line\":22,\"ch\":34}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":5}],[{\"line\":17,\"ch\":24},{\"line\":17,\"ch\":29}],[{\"line\":23,\"ch\":1},{\"line\":23,\"ch\":6}],[{\"line\":32,\"ch\":1},{\"line\":32,\"ch\":6}],[{\"line\":47,\"ch\":45},{\"line\":47,\"ch\":50}],[{\"line\":92,\"ch\":22},{\"line\":92,\"ch\":27}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":31,\"ch\":13},{\"line\":31,\"ch\":18}],[{\"line\":48,\"ch\":10},{\"line\":48,\"ch\":15}],[{\"line\":91,\"ch\":33},{\"line\":91,\"ch\":38}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":5}],[{\"line\":17,\"ch\":24},{\"line\":17,\"ch\":29}],[{\"line\":23,\"ch\":1},{\"line\":23,\"ch\":6}],[{\"line\":32,\"ch\":1},{\"line\":32,\"ch\":6}],[{\"line\":47,\"ch\":45},{\"line\":47,\"ch\":50}],[{\"line\":92,\"ch\":22},{\"line\":92,\"ch\":27}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":5}],[{\"line\":17,\"ch\":24},{\"line\":17,\"ch\":29}],[{\"line\":23,\"ch\":1},{\"line\":23,\"ch\":6}],[{\"line\":32,\"ch\":1},{\"line\":32,\"ch\":6}],[{\"line\":47,\"ch\":45},{\"line\":47,\"ch\":50}],[{\"line\":92,\"ch\":22},{\"line\":92,\"ch\":27}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":51,\"ch\":12},{\"line\":51,\"ch\":18}],[{\"line\":52,\"ch\":11},{\"line\":52,\"ch\":17}],[{\"line\":53,\"ch\":10},{\"line\":53,\"ch\":16}],[{\"line\":51,\"ch\":12},{\"line\":51,\"ch\":18}],[{\"line\":52,\"ch\":11},{\"line\":52,\"ch\":17}],[{\"line\":53,\"ch\":10},{\"line\":53,\"ch\":16}],[{\"line\":51,\"ch\":12},{\"line\":51,\"ch\":18}],[{\"line\":52,\"ch\":11},{\"line\":52,\"ch\":17}],[{\"line\":53,\"ch\":10},{\"line\":53,\"ch\":16}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}],[{\"line\":18,\"ch\":22},{\"line\":18,\"ch\":27}],[{\"line\":27,\"ch\":21},{\"line\":27,\"ch\":26}],[{\"line\":37,\"ch\":10},{\"line\":37,\"ch\":15}],[{\"line\":39,\"ch\":10},{\"line\":39,\"ch\":15}],[{\"line\":47,\"ch\":62},{\"line\":47,\"ch\":67}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":5}],[{\"line\":63,\"ch\":17},{\"line\":63,\"ch\":22}],[{\"line\":71,\"ch\":0},{\"line\":71,\"ch\":5}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":5}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":5}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":5}],[{\"line\":81,\"ch\":0},{\"line\":81,\"ch\":5}],[{\"line\":82,\"ch\":0},{\"line\":82,\"ch\":5}]]"} !@%STYLE%@!
13.1 Recycling objects to reduce memory consumption
In this section you’ll implement a reusable asynchronous object pool. This should be used in cases where the recycling of objects benefits the reduction of memory consumption. Minimizing the number of GC generations allows your program to enjoy better performance speed. Figure 13.1, repeated from chapter 12, shows how to apply concurrent Producer/Consumer patterns, from Listing 12.9, to compress and encrypt a large file in parallel.
Figure 13.2 An object pool can asynchronously handle multiple concurrent requests for reusable objects from multiple consumers. The consumer then sends the object back to the object pool when it’s done with the work. Internally, object pool generates a queue of objects using a given factory delegate. These objects are then recycled to reduce memory consumption and the cost of new instantiation.
![]()