[C# Performance] The using macro and how it can improve memory utilization in your application.

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
In C# one of the most common macros is the using macro. It has two uses, the first use is importing packages from the system library and packages installed from nuget. For example using System.Console; however the second use is when you want to temporary keep a file and certain variables in memory. It’s easier to remember and faster to write than the old cleanup code that had to be written in older versions of C#.

How to use the using macro…

Consider the following method. It is an infinite loop that “GETs” a webpage and prints the result several times. We do not want to keep this data in memory when we’re done with it for performance reasons. If we were to keep the response stream in memory, it could fill up quickly overtime given the infinite loop and create a memory leak. The using macro performs automatic cleanup to avoid this situation. Look at the following code example to see it in action…

C#:
while (true)
{
            // Create a WebRequest
            var request = WebRequest.Create($"https://www.google.com/");
            request.Method = "GET";

            // Run request and store the response
            var dataStream = request.GetRequestStream();
            var response = request.GetResponse();

            using (dataStream = response.GetResponseStream())
            {
                // Open the stream using a StreamReader for easy access. 
                var reader = new StreamReader(dataStream);
                // Read the content. 
                Console.Write(reader.ReadToEnd());
            }
}
Conclusion

The using macro provides C# programmers a powerful solution to easily cleanup memory after working with files and other I/O bound tasks.
 
  • Like
Reactions: Jinder