<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Karol Rossa on Medium]]></title>
        <description><![CDATA[Stories by Karol Rossa on Medium]]></description>
        <link>https://medium.com/@karol.rossa?source=rss-9f0a071996------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JhgS7ByYd8CZIcIaGM1X5w.jpeg</url>
            <title>Stories by Karol Rossa on Medium</title>
            <link>https://medium.com/@karol.rossa?source=rss-9f0a071996------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:31:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karol.rossa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Array Pool]]></title>
            <link>https://medium.com/@karol.rossa/array-pool-5eb720d1f861?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eb720d1f861</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 12:21:19 GMT</pubDate>
            <atom:updated>2023-03-23T15:35:28.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Array Pool main" src="https://cdn-images-1.medium.com/max/1024/1*JQsO0EJwa7v21530We4Tzg.jpeg" /></figure><p>Nowadays, we rarely use arrays. In most cases, we use List&lt;T&gt;, which provides more functionality and is based on an array under the hood. But there are situations when performance is the key while dealing with many objects.</p><blockquote>What has surprised me is that a plain array is twice as efficient as a List, and it can still be optimized with ArrayPool.</blockquote><p>In this article, I will show you how to use ArrayPool with code examples and benchmarking performance.</p><p><a href="https://github.com/krossa/ArrayPoolBenchmark"><strong>Code Repository</strong></a></p><h4><strong>What is ArrayPool</strong></h4><p>ArrayPool is a resource pool that allows reusing instances of array types. You can use it to Rent and Return buffers(arrays). It will improve performance when you frequently create and destroy arrays, which are heavy on memory and <a href="https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60">GARBAGE COLLECTOR</a>. This class is thread-safe, and you can use it concurrently. While returning to the pool, you can choose to clear or not array content. Clearing will take more time, but your situation might require getting an empty array each time.</p><h4><strong>How to use it</strong></h4><p>There are two ways of accessing arrays from pool memory.</p><p>The first and simplest is to use the ArrayPool <strong>Shared</strong> property.</p><blockquote><em>ArrayPool&lt;T&gt;.Shared</em></blockquote><p>You will get the default implementation of the pool. It contains arrays of different sizes. It can return a larger array than you have requested but certainly not smaller. A shared pool is a convenient way to reuse arrays, but there are better ones.</p><p>The more efficient way is to initialize your pool using create methods.</p><blockquote><em>ArrayPool&lt;T&gt;.Create()</em></blockquote><blockquote><em>ArrayPool&lt;T&gt;.Create(int maxArrayLength, int maxArraysPerBucket)</em></blockquote><p>Create method returns a custom instance of the pool. You must cache it to access it from different locations to reuse it. The parameterized method can help achieve the best performance. It will create an instance that groups arrays of length no more than <em>maxArrayLength </em>into buckets of size <em>maxArraysPerBucket.</em></p><p>Take advantage of array pooling in C# to reduce allocations and improve the performance of your applications.</p><h4><strong>Benchmark</strong></h4><p>This is a straightforward test. We will compare the differences between creating a new array and renting it from the pool. In each case, we will iterate over a collection of 1_000_000 elements. I will also include List&lt;T&gt; in the benchmark to show the performance advantages of arrays.</p><p><a href="https://github.com/krossa/ArrayPoolBenchmark"><strong>Code Repository</strong></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8394ba78c37913ef2495d8c17bf10dcf/href">https://medium.com/media/8394ba78c37913ef2495d8c17bf10dcf/href</a></iframe><figure><img alt="Benchmark results" src="https://cdn-images-1.medium.com/max/1024/1*lMXJkTQa7dN0JSWQ8LiYcA.png" /><figcaption>benchmark</figcaption></figure><h4><strong>Conclusions</strong></h4><p>What has surprised me the most is that a plain array is twice as efficient as a List in terms of speed and memory usage. And it can still be optimized with ArrayPool. Using a pool is obviously the way to go.</p><p>There is a noticeable time difference between using a standard array and one from the pool. The time difference is the time required to allocate memory when creating a new array each time. Of course, there is also a difference in memory allocation. ArrayPool does not need to allocate new memory. It reuses the same block.</p><p>As a warning, I have added ‘Custom Pool Without Caching’ so you can see what happens when you create a new pool each time. It is basically the same thing as creating a new array each time.</p><p>In this simple example, it is hard to show the performance difference between shared and custom ArrayPool. It would be noticeable when many arrays of different sizes are used.</p><blockquote>Using ArrayPool may not always be the most convenient, but sometimes it can save you a lot of computing power when needed.</blockquote><h3>EDIT</h3><p>After finishing the article, I wondered, ‘what if we initialize the List with a fixed size.’ The same way we initialize arrays. I have added the missing benchmark (ListWithSize <a href="https://github.com/krossa/ArrayPoolBenchmark"><strong>Code Repository</strong></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*HN1EnPVuXrJd0DflvOO8ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvuaQukEQ2nGXGs59DvUYA.png" /></figure><p>The result is better than the standard list, but an array is still a much better choice while writing efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eb720d1f861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ValueTask vs. Task]]></title>
            <link>https://medium.com/@karol.rossa/valuetask-vs-task-5fb4f9c6517?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb4f9c6517</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 18:38:17 GMT</pubDate>
            <atom:updated>2022-12-15T12:25:12.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="ValueTask vs. Task logo" src="https://cdn-images-1.medium.com/max/1024/1*eI71-8SY92N-Yyakk-BPxw.png" /></figure><p>We have already covered <a href="https://medium.com/@karol.rossa/asynchronous-programming-73b4f1988cc6">the asynchronous paradigm</a> and <a href="https://medium.com/@karol.rossa/asynchronous-performance-1be01a71925d">performance comparison of async vs. sync API calls</a>.<br>Today I will show you how to save memory using ValueTask. In a previous story, we talked about <a href="https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60">Garbage Collector</a> and how it can slow down the application during memory collection.</p><p>ValueTask should be used in an asynchronous method that can execute synchronously. What the hell is that? The simplest example I will use is a method that will most likely return value from cache and, if necessary, make an async call to an external resource. In layman’s terms, if your async method can return without reaching the await statement, use ValueTask as the return type.<br>If you are interested in why ValueTask is more efficient and to find the hidden cost of using Task, keep reading till the end :)</p><p><a href="https://github.com/krossa/ValueTaskBenchamrk"><strong>Code Repository</strong></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87aa0ae4ed56bf8a1dd8a8d3f0dbd49f/href">https://medium.com/media/87aa0ae4ed56bf8a1dd8a8d3f0dbd49f/href</a></iframe><p>As you can see, the only difference between GetData<strong>WithValueTask</strong>Async and GetData<strong>WithTask</strong>Async is the return type. Respectively ValueTask vs. Task.</p><p>For benchmark, I will use <a href="https://benchmarkdotnet.org/articles/overview.html">benchmarkdotnet.org</a> with two attributes</p><ul><li>[Benchmark] — marks method for evaluation</li><li>[MemoryDiagnoser] — adds information about memory allocation</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c12cc7101231dd3a65d4585a479cc2fd/href">https://medium.com/media/c12cc7101231dd3a65d4585a479cc2fd/href</a></iframe><p>It is a simple class that runs each method from a repository.</p><h3>Results</h3><figure><img alt="ValueTask vs. Task benchamrk" src="https://cdn-images-1.medium.com/max/1017/1*kXl2fbcL_vq8qGsIxYjjtg.png" /><figcaption>ValueTask vs. Task benchamrk</figcaption></figure><p>Execution time is nearly the same for each case. What matters is memory allocation. Only the Task method has caused memory allocation on the heap. Value from the benchmark represents allocation per single call. So if the Task method is called multiple times, it can significantly increase memory allocation, which has to be released by <a href="https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60">Garbage Collector</a>. Additionally, each call creates a separate Task object that needs to be handled individually by GC. This happens because Task is a reference type that always gets allocated on the heap, which is the hidden cost of using Task over ValueTask.</p><blockquote>So what is a ValueTask, and why is there no memory allocation in our example?</blockquote><p>ValueTask is a value type struct that wraps a Task&lt;TResult&gt; and a TResult, only one of which is used. As we know, struct, by default, gets allocated on the stack, not the heap. Stack allocation is cheaper because it gets released automatically, not by GC.</p><p>Under the hood, it is a discriminated union and can return one of two things. Either a plain value TResult (value taken from cache) or a Task&lt;TResult&gt; (returned by async GetData). In our example, a task must be created every 1 hour when the cache expires. Every other time method returns a plain TResult value without any excessive memory allocation</p><p>There are also drawbacks to using ValueTask, so you must be careful when deciding what to use. There are a couple of scenarios when ValueTask can’t be used:</p><ul><li>Awaiting the instance multiple times.</li><li>Calling AsTask multiple times.</li><li>Using .Result or .GetAwaiter().GetResult() when the operation hasn’t yet completed, or using them multiple times.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb4f9c6517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Performance]]></title>
            <link>https://medium.com/@karol.rossa/asynchronous-performance-1be01a71925d?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be01a71925d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 08:12:12 GMT</pubDate>
            <atom:updated>2022-12-15T12:26:19.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="async vs. sync benchmark" src="https://cdn-images-1.medium.com/max/1024/1*YecDuj1Yd-M98hrh-y7aXA.jpeg" /></figure><p>In a <a href="https://medium.com/@karol.rossa/asynchronous-programming-73b4f1988cc6">previous article</a>, I have described how async works. Today I would like to talk about async performance compared to synchronous calls in .NET 6 Web API on the Kestrel server. <a href="https://medium.com/@karol.rossa/valuetask-vs-task-5fb4f9c6517">Here you can check the difference in memory allocation.</a></p><p>.NET 6 allows me to prepare necessary code in just a couple of lines. I will use a simple tool for measuring performance, the apache<strong> </strong><a href="https://httpd.apache.org/docs/2.4/programs/ab.html">benchmark</a>.</p><p><a href="https://github.com/krossa/AsyncBenchmark"><strong>Code Repository</strong></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81b8612ebee8a2dd3b2acc2083a0a588/href">https://medium.com/media/81b8612ebee8a2dd3b2acc2083a0a588/href</a></iframe><p>Code exposes two endpoints and adds to each request a 2-second delay. Deley represents calls to external resources like the database. I have also added a background thread to monitor ThreadPool activity, which I will explain further in the article.</p><ul><li>(sync) — An old-fashioned call. A request is delayed by Thread.Sleep, which blocks the thread.</li><li>(async) — Not so new guy on the block. This time Task.Delay imitates an asynchronous call, which does not block the thread.</li></ul><p>Let’s take a look at the apache benchmark command:</p><blockquote><em>ab -n 100 -c 100 -k -s 120 “</em><a href="http://localhost:5000/async"><em>http://localhost:5000/async</em></a><em>&quot;</em></blockquote><ul><li>c — Number of concurrent clients working simultaneously.</li><li>n — Number of requests to perform for the benchmarking session.</li><li>k — Enable the HTTP KeepAlive feature, i.e., perform multiple requests within one HTTP session. Default is no KeepAlive.</li><li>s — Maximum number of seconds to wait before the socket times out.</li></ul><h3>Comparison</h3><p>I have performed tests for different numbers of concurrent clients to compare results with other workloads. After an initial test on 100 clients, I had to add a background thread to display current thread activity. The reason for that was too similar performance between async and sync requests. I know Kestrel is not the best performance server, but we will be able to see trends.</p><h4>100 concurrent clients</h4><figure><img alt="100 clients statistics" src="https://cdn-images-1.medium.com/max/1024/1*Pn6d2JyG-3-eGGrnyE6jCA.png" /><figcaption>100 clients statistics</figcaption></figure><figure><img alt="100 clients graphs" src="https://cdn-images-1.medium.com/max/1024/1*WnNk8Rj-4OasvG2V3QMdNg.png" /><figcaption>100 clients graphs</figcaption></figure><p>With a low number of concurrent requests, the server can handle async and sync requests similarly. Because of that, I had added a background thread that monitors thread activity and checks status every second. Thread switching is performed so fast for controller asynchronous action that it almost looks like no threads are being used. This will be the same even for a more significant number of concurrent clients. For 100 clients, this was the biggest difference for synchronous action. At peak workload, the sync method had to block 100 threads. Additionally, async calls quickly reached maximum performance at 50 requests per second and maintained it.</p><h4>1 000 concurrent clients</h4><figure><img alt="1 000 clients statistics" src="https://cdn-images-1.medium.com/max/1020/1*zPAa0ToE06REDQ5tMqOe-w.png" /><figcaption>1 000 clients statistics</figcaption></figure><figure><img alt="1 000 clients graphs" src="https://cdn-images-1.medium.com/max/1024/1*9jPoB0WTvbAF35aV4lc2Qw.png" /><figcaption>1 000 clients graphs</figcaption></figure><p>With 1000 concurrent clients, async has already outperformed sync calls in every possible way. Sync has performed significantly worse and had to block up to 450 threads during peak workload. For async calls, we can observe that graphs have a similar shape to 100 clients. Total time grows linearly, and a maximum number of 500 requests per second was again obtained quickly and maintained.</p><h4>10 000 concurrent clients</h4><figure><img alt="10 000 clients statistics" src="https://cdn-images-1.medium.com/max/1020/1*FFE-X6TdAmU-tRGmSJ6ckg.png" /><figcaption>10 000 clients statistics</figcaption></figure><figure><img alt="10 000 clients graphs" src="https://cdn-images-1.medium.com/max/1024/1*AruvHO6KW9eKz0EPhro8Iw.png" /><figcaption>10 000 clients graphs</figcaption></figure><p>For 10 000 concurrent clients, we are missing statistics for a synchronous controller action. This is because the Kestrel server could not handle this workload. For async calls, graphs again have a similar shape, and the same goes for a number of blocked threads, basically none.</p><h3>Conclusions</h3><p>As expected, async outperforms sync in every possible way. Numbers don’t lie :) I can imagine that a more powerful server could handle more synchronous requests simultaneously. But at the same time, we can see that Kestrel could process workload for async calls without sweat. We can draw one more conclusion by looking at the startup process for sync and async calls.</p><figure><img alt="sync startup" src="https://cdn-images-1.medium.com/max/791/1*sW9zvLs7bfh4XGBb44P0gA.png" /><figcaption>sync startup</figcaption></figure><figure><img alt="async startup" src="https://cdn-images-1.medium.com/max/786/1*zuo0aozrp1CE386_CNmHrQ.png" /><figcaption>async startup</figcaption></figure><p>The server needs to ‘warm up’ before handling sync calls at maximum capacity. On the other hand, it can process async calls at full capacity from the beginning.</p><p>We all have expected where this is going before reading this article. Use async instead of sync :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be01a71925d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Programming]]></title>
            <link>https://medium.com/codex/asynchronous-programming-73b4f1988cc6?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b4f1988cc6</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Tue, 17 May 2022 15:16:33 GMT</pubDate>
            <atom:updated>2022-12-15T10:40:25.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Asynchronues logo" src="https://cdn-images-1.medium.com/max/1024/1*adu4Cn5jSvca96rezI6jqg.jpeg" /></figure><p>I want to cover a couple of things regarding asynchronous programming in .NET. The main concept can also be applied to other languages, so feel free to read through. We will talk about common misconceptions of async and parallel programming and how to decide on the proper approach. I will also describe how async works. In the following articles, I will show an example of a performance boost that you can achieve using an asynchronous approach. We will also discuss how to use async in synchronous context. Hopefully, you will never have to do it :)</p><ul><li><a href="https://medium.com/@karol.rossa/asynchronous-performance-1be01a71925d">async vs. sync performance</a></li><li><a href="https://medium.com/@karol.rossa/valuetask-vs-task-5fb4f9c6517">ValueTask vs. Task</a></li></ul><h3>Async vs. Parallel</h3><p>In parallel programming, work is done in parallel :) at the same time. The amount of work that can be done simultaneously depends on the number of cores of the processor. It is most useful when dealing with a job heavy on CPU processing time and can be split into smaller chunks.</p><figure><img alt="Parallel Processing" src="https://cdn-images-1.medium.com/max/1024/1*g7BA4e0RXaS2_wR3cr0opw.png" /><figcaption>Parallel Processing</figcaption></figure><p>We can implement asynchronous code even on one core, but it can take advantage of multi-core machines. Async is not about doing multiple units of work simultaneously but switching between tasks that currently need computing time. It can save a lot of processing time when dealing with anything external to the process, like calls to DB or HTTP Clients. After making a call to a network resource using HTTP Client, we need to wait for a response. Instead of blocking the thread, we could complete additional work on it.</p><figure><img alt="Asynchronous Processing" src="https://cdn-images-1.medium.com/max/1024/1*2yaD3MPUxfMCNMXIG0RkLA.png" /><figcaption>Asynchronous Processing</figcaption></figure><h3>What is Async</h3><p>Asynchronous programming is about releasing threads awaiting external resources so we can use them for other work. I have mentioned before that async can work on a single thread, but today almost all machines are equipped with multi-core processors. I will show you how we can benefit from this. Also, keep in mind that we have to use async from top to bottom of the call stack while writing async code.</p><p>Under the hood, async creates a state machine. You can find countless articles comparing async to boiling water or preparing food in the kitchen. This time we will talk about how it works. Let’s look at the example below and go over it step by step.</p><p><a href="https://github.com/krossa/AsyncSample"><strong>Code Repository</strong></a></p><blockquote><em>Dump() is my custom function for printing information into console</em>.</blockquote><figure><img alt="Code Version A" src="https://cdn-images-1.medium.com/max/1024/1*cP-5KwPN6MHu2eoyqeQoDQ.png" /><figcaption>Code Version A</figcaption></figure><figure><img alt="Code Version B" src="https://cdn-images-1.medium.com/max/916/1*oGxikHDZmjd99Udc0MlbKw.png" /><figcaption>Code Version B</figcaption></figure><p>Code B is different only by the amount of work done in ProcessAsync before awaiting task from ExternaAsync.</p><figure><img alt="Result A" src="https://cdn-images-1.medium.com/max/731/1*1ypBEXvvPKvupExmW7gmXg.png" /><figcaption>Result A</figcaption></figure><figure><img alt="Result B" src="https://cdn-images-1.medium.com/max/730/1*ldeoBkMfULXY6fFIzCjYQw.png" /><figcaption>Result B</figcaption></figure><p>1 The entry point to our application. Thread 1 takes care of the work.</p><p>2 Nothing exciting yet, just initializing our process and calling the ExternalAsync function like a standard synchronous function. Thread 1 also completes this work.</p><p>3 Initialize external work synchronously still on thread 1. But now, we hit the first await in our program. Task.Delay(100) symbolizes an async call to external resources like the HttpClient.GetAsync function. At this time, work is delegated to an external driver, and we have to wait for the result. But instead of waiting and doing nothing, we immediately return to the ProcessAsync function.</p><p>After returning to ProcessAsync, we can complete additional work while the HTTP request runs. We can also notice that async can work in parallel. Now we will consider both cases. <br><strong>A (1_000)</strong> — a small amount of work that is done before ExternalAsync can finish.<br><strong>B (1_000_000_000)</strong> — a heavy workload that takes more time to finish than ExternalAsync</p><h4>Version A</h4><p>4 In the output, we can see that both checkpoints ‘PROCESS more work 1/2’ appear one after the other on thread 1. We have nothing else to do when we hit await on the task. Task has not been resolved yet, and we need to wait for it. So thread 1 is released to the thread pool and can be used for something different, like handling another call to the controller.</p><p>5 External work is finally done, and execution continues on a new thread 5. After finalizing work in the ExternalAsync method, we return the result to the ProcessAsync.</p><p>6 Only external call is executed in parallel, but this is handled by some external driver and not by our application. In this example, work in ProcessAsync continues on thread 5. Our code is executed in sequence, but we do not block thread 1 when waiting for an async call. This alone gives our application a performance boost.</p><h4>Version B</h4><p><strong>4–5</strong> After investigating the output, we can see that the task in the ExternalAsync method has finished before more work in the ProcessAsync and was executed in parallel.</p><ul><li>Thread_Id(1) PROCESS more work 1</li><li>Thread_Id(5) External finalize</li><li>Thread_Id(1) PROCESS more work 2</li></ul><p>We have achieved parallel processing without any additional code, just by knowing how async works and calling ExternalAsync, and awaiting its task later in code. We can see it clearly because of different thread ids (1–5). If we awaited ExternalAsync on line 4, parallelization of our code would not be possible.</p><p>6 In this example, when hitting await in the ProcessAsync, the task was already resolved, so we can continue work on the same thread 1. I hope that we will be able to write better asynchronous code that also takes advantage of parallelization with this knowledge.</p><h3>How Async Works</h3><p>Three parts define asynchronous: async, await, and Task. Async creates a state machine with one initial state. Each await adds one additional state, so the number of states equals the number of await + 1. The Task is a wrapper around the result. The Task contains information on the status and result and can be awaited.</p><p>We have learned that each await adds a state to our state machine. We should avoid it if possible. For example, when adding an abstraction layer with setup or logging (like PROXY), we are just passing through a call to an async method. Keep in mind that we have to await all Tasks in our code base eventually. If an asynchronous method that is not eventually awaited throws an exception, that exception will be lost, and we will not have any recollection of an error.</p><figure><img alt="Returning Task" src="https://cdn-images-1.medium.com/max/654/1*IDM3AT77galqTsFyhaqWJA.png" /><figcaption>Returning Task</figcaption></figure><h3>Tips and Notes</h3><p>Asynchronous programming is a vast topic. I can’t cover everything in a single article. I have mentioned stuff that will allow you to write efficient async code. Now we will talk about a couple more guidelines. Again we will touch on the basics of each topic.</p><h4>Cancellation Token</h4><p>When writing async code for your use, you can omit to pass the Cancellation Token if you are not going to use it. It allows you to cancel long-running Tasks. It would be best to remember it when creating libraries for general use. Just add it as the last parameter with the default value.</p><figure><img alt="Cancellation Token" src="https://cdn-images-1.medium.com/max/1024/1*yXYLNMba672KGwI0_7QG8Q.png" /><figcaption>Cancellation Token</figcaption></figure><h4>SynchronizationContext and ConfigureAwait</h4><p>The main aspect of SynchronizationContext is to provide a way to queue a unit of work to a context. Context is not bound to a single thread and can be passed between them. It is primarily used in applications with UI like WPF or Windows Forms. It allows you to do background work and, while returning, make changes in the UI thread thanks to passing SynchronizationContext. A big change in .NET Core was to remove SynchronizationContext from ASP.NET.</p><p>ConfigureAwait is used to avoid forcing the callback to be invoked on the original context. By default, .NET uses the original context. Not passing the original context to the callback function has many benefits.</p><blockquote><em>ConfigureAwait(continueOnCapturedContext: false)</em></blockquote><p><strong>Improved Performance</strong>. When all callbacks are queued to the same context, it adds delay in executing them in order. Sometimes just checking for SynchronizationContext can add unwanted lag into the path.</p><p><strong>Avoid Deadlocks. </strong>In some rare situations, when async code is executed synchronously (.Result) and SynchronizationContext limits the number of operations that can run on it to 1. Imagine a situation when the main thread uses the context. The async method is invoked on it with .Result which makes it a synchronous call that blocks the main thread. Now the async method finishes on a different thread and can’t access context because it is blocked in the main thread.</p><p>You should always avoid forcing the use of the original context if not necessary by configuring await to false.</p><blockquote><em>client.AsyncCall().ConfigureAwait(fasle)</em></blockquote><h4>ValueTask</h4><p>ValueTask is a struct that wraps either a value or a task and returns it. It should be used as a return type for methods that could run either synchronously or asynchronously. For example, a method that can retrieve value from cache or needs to make an async call to an external resource.</p><figure><img alt="ValueTask" src="https://cdn-images-1.medium.com/max/1024/1*a_Gfc1dxH_L-5e5LxH9VvQ.png" /><figcaption>ValueTask</figcaption></figure><p>Task allocation takes more resources than returning a plain value. If a method is executed synchronously, there is no need to create a Task. So ValueTask wraps a plain integer value. This works because ValueTask implements necessary methods, especially GetAwaiter(), and can be consumed by the caller as Task. <a href="https://medium.com/@karol.rossa/valuetask-vs-task-5fb4f9c6517">Here you can check the difference in memory allocation.</a></p><p>There are just a couple of operations that should not be performed on a ValueTask instance:</p><ul><li>Awaiting the instance multiple times.</li><li>Calling AsTask multiple times.</li><li>Using .Result or .GetAwaiter().GetResult() when the operation hasn’t yet completed, or using them multiple times.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b4f1988cc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/asynchronous-programming-73b4f1988cc6">Asynchronous Programming</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT 3-way merge]]></title>
            <link>https://medium.com/@karol.rossa/git-3-way-merge-addc2728c300?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/addc2728c300</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[merge]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 12:37:16 GMT</pubDate>
            <atom:updated>2022-03-16T12:37:16.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BWRlQGZUFFt-qAxBqS5zw.png" /></figure><p>Git is an excellent tool for collaborative work on a shared codebase. As we all know, more than one person will have to work on the same file at some point in time. Working together can lead to merge conflicts which further can cause disasters. Really, I am not exaggerating :)</p><p>A 3-way merge (diff3) can prove to be a life savior in those situations. It can handle more cases automatically than default diff2. Additionally, it is helpful during manual merging. I am using <a href="http://gitextensions.github.io/">git-extensions</a> for handling git stuff and <a href="http://kdiff3.sourceforge.net/">kdiff3</a> as a merge tool. I will go over a simple example to demonstrate how to use it. Afterward, I will explain the algorithm.</p><blockquote>You can enable diff3 by running git command</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb381a2572f58ceb27b12b7df767b6c5/href">https://medium.com/media/bb381a2572f58ceb27b12b7df767b6c5/href</a></iframe><blockquote>or by updating .gitconfig file</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e972643772eef5ab02881a110ee2a869/href">https://medium.com/media/e972643772eef5ab02881a110ee2a869/href</a></iframe><h3>Case Study</h3><p>Let’s start with implementing a simple repository that gets Private accounts and push it to the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*IeYSRiqJWNMFgO6ErYM99Q.png" /><figcaption>initial code with bug</figcaption></figure><p>You have probably noticed an obvious bug — GetPrivateAccounts returns Public accounts. Do not worry. We will handle it in a moment.</p><p>Now we got a request for a new feature. We need to add the active filter to our query. Let’s implement it on a new feature branch without pushing changes to the main because it needs to be tested first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*tECxnvdIjksNFh8HPK7FTg.png" /><figcaption>new feature</figcaption></figure><p>In the meantime, someone noticed Private/Public bug. He implements it on a different branch and pushes the change to main before our feature is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*kSads7riE831SO4N5AuHag.png" /><figcaption>bug fix</figcaption></figure><p>When merging main to our feature branch, we get a warning about conflict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ZObQaNPkAqfDu_AabxCt9A.png" /><figcaption>list of conflicts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR1HvNJvVEi64MUnu7kUmw.png" /><figcaption>3-way merge</figcaption></figure><p>A — Original file before new feature and bug fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*TWHfX8vOWD3u52n_bd8cKQ.png" /><figcaption>base</figcaption></figure><p>B — Feature branch with IsActive filter that we want to merge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*TkSOKhoD7TRgGORC57CMKg.png" /><figcaption>local</figcaption></figure><p>C — Bug fix that is already merged into main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*pn0ym42J2LJ5_WuJVFSD9A.png" /><figcaption>remote</figcaption></figure><p>D — Result of the merge. At the moment, it shows conflict because both changes happened on the same line.</p><p>We can’t just pick any of the versions because none contains all the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*0kIz6pJs4FC8JBIUZW0Y8w.png" /><figcaption>local and remote</figcaption></figure><p>We need to choose a version and add changes from a second version. We can see that line is now marked with ‘m’ for modified :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*hwZYjAM22JtUEinFxgg91g.png" /><figcaption>modified</figcaption></figure><p>Finally, after manually resolving the conflict, we get the final version of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*cmgU3IUCQM0Deg0k9-cvCA.png" /><figcaption>final code</figcaption></figure><h3>Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jN1Y-zbIrpcwYaDZJRc8Mg.png" /></figure><p>For a 3-way marge to occur, the base file must be changed independently on two different branches. Then we follow a couple of simple rules:</p><ul><li>line does not change -&gt; goes to the merged file</li><li>line changes only in one file -&gt; change goes to the merged file</li><li>line changes in both files but remains the same -&gt; change goes to the merged file</li><li>line changes in both files and is different -&gt; unresolved conflict</li></ul><p>Let’s go over our example line by line:</p><p>A4 — Did not change, so it is used in the merged file.</p><p>B5 — Was changed only in local version to B6. The merged file will use B6.</p><p>C3 — Was changed only in remote version to C4. The merged file will use C4.</p><p>D2 — Was changed in both files to different versions. We will need to resolve this conflict manually.</p><p>E6 — Was changed in both files to the same value of E7. The merged file will use E7.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=addc2728c300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging 101 in Visual Studio 2022]]></title>
            <link>https://medium.com/@karol.rossa/debugging-101-in-visual-studio-2022-8cc2922acf89?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cc2922acf89</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[visual-studio]]></category>
            <category><![CDATA[debug]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 20:03:07 GMT</pubDate>
            <atom:updated>2022-03-14T13:44:48.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7pozkiKVeyiPKFUpYQFlQ.jpeg" /><figcaption>Debug</figcaption></figure><p>Debugging can be an annoying and time-consuming task. But using the proper tools, you can make your life much easier. In most modern IDEs, we have access to a similar set of tools. So this knowledge is easily transferable to different advanced code editors. Today let’s talk about the basics of debugging in professional IDE. This article will take a closer look into Visual Studio 2022 as it is the newest edition from Microsoft.</p><p>I assume that you have a basic knowledge of creating breakpoints or continuing execution. I encourage you to play around with the functionality. We will not go over each filter and specific option. We will focus on three essential features. How to use them and what value they have.</p><ul><li>breakpoints</li><li>application state</li><li>call stack</li></ul><h3>Breakpoints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*FKBgTExU7zk-taOAQwenAA.png" /><figcaption>breakpoints in code</figcaption></figure><ol><li>A full circle represents a standard breakpoint. The debugging process will always stop on this code line, nothing special here.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iipy7eTGmYzRjCCZ7IqRHA.png" /><figcaption>breakpoints condition</figcaption></figure><p>2. Circle with a small plus sign. The process will stop on this breakpoint only if a specified condition is met. It is helpful while iterating over large collections, and we are interested only in a particular element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*_8IAGs_abhZcEAJNsl6V3A.png" /><figcaption>breakpoints action</figcaption></figure><p>3. Diamond shape stands for action. You can choose if the process will stop here. But the primary purpose is to print a value to the output window without adding extra code. Let’s be honest how many times we have left in code ‘Console.WriteLine’. You can use string interpolation to print out a variable’s value.</p><p>4. Yellow arrow represents the current position of the process. The neat thing is that you can move it in any direction. For example, if you forgot to step into a method, you can drag an arrow just before the call to AddProduct and fix your mistake. You can also combine conditions with actions.</p><h4>Breakpoints window</h4><p>The image is pretty much self-explanatory. You can access it from the top menu Debug-&gt;Windows-&gt;Breakpoints. When you hover over a button, you will see a clear description. Below we can see a list of all breakpoints in our solution. A couple of most handy features are:</p><ul><li>enable/disable a breakpoint</li><li>remove a breakpoint</li><li>edit label</li><li>search for a breakpoint using an advanced filter</li></ul><p>They are also useful while navigating through code. You can move to the desired source code by double-clicking on an endpoint. You can even go to the disassembly to check low-level instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SUy9DHonYeA7RUPG9a-bw.png" /><figcaption>breakpoints disassembly</figcaption></figure><h3>Application State</h3><p>You have a couple of options under your disposal to check the current state of your application.</p><ul><li>locals</li><li>watch</li><li>immediate window</li></ul><p>You can access all those windows again from the top menu Debug-&gt;Windows.</p><h4>Locals</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*stcLB21pn2794B4BWezkFA.png" /><figcaption>locals</figcaption></figure><p>Locals contain all variables from the current scope. Complex types have access to all nested properties, and the same goes with elements from any collection. I have expanded to the first element from products in the order in the picture above. During debug mode, you can change the value of each property by double-clicking on it. This feature, combined with a moving yellow arrow representing the current position, can be a real-time saver, especially in big legacy solutions.</p><h4>Watch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*qnnb2LbdawALm08maTpvbA.png" /><figcaption>watch</figcaption></figure><p>The watch allows you to define the items that you need to follow. You can even apply LINQ expression on the collection if required. You can also update values here.</p><h4>Immediate Window</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*xd22fHGjqSArfYFyCQbBIA.png" /><figcaption>immediate window</figcaption></figure><p>The ‘immediate window’ allows you to write any C# statement with variables from the current scope. Again it can be helpful to try something without changing code and rerunning the whole application.</p><h3>Call Stack</h3><p>As you can imagine, the Call Stack window shows you the current call stack. You can use it for navigation by double-clicking each row. The yellow arrow again represents the current position of the process. And the smaller green arrow show position where you have navigated. It might not look like a lot, but you will fully appreciate it when debugging a vast legacy application written a long time ago.</p><h3>Notes</h3><p>Again I encourage you to play around with the functionality we have just checked out. Those features can look like overkill in small console applications. On the other hand, they are a true time-saver in gargantuan solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cc2922acf89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IDisposable]]></title>
            <link>https://medium.com/@karol.rossa/we-have-already-covered-memory-management-topics-with-garbage-collection-and-implementing-ce00cdfb6d5c?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce00cdfb6d5c</guid>
            <category><![CDATA[disposable]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[finalizers]]></category>
            <category><![CDATA[destructor]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 18:17:45 GMT</pubDate>
            <atom:updated>2022-06-22T14:25:10.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npPh8RzDqI3jEZHwEHM0sw.png" /></figure><p>We have already covered memory management topics with <a href="https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60">Garbage Collection</a> and implementing <a href="https://medium.com/@karol.rossa/net-finalizers-3e2a9f85ae4">Finalizers</a> in .NET. This time we will talk about how to use IDisposable patterns. Dispose is the best tool for releasing unmanaged resources. Also, whenever you use an object that implements an IDisposable interface, be sure to dispose of it.</p><p>There are additional reasons to use Dispose like free allocated memory, removing an item added to a collection, or signaling the release of a lock. Implementation should be idempotent. Subsequent calls shouldn’t cause an exception and basically shouldn’t do anything.</p><h3>Using Disposable Object</h3><p>First, let us refresh our memory on how to consume the disposable object. We had to create a ‘using statement’ scope in distant Framework days. It gave us access to an instance within the braces scope. But if we had to use another disposable object within, it led to nasty nesting ;)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cac0f263127b886300ebaa52b7717d81/href">https://medium.com/media/cac0f263127b886300ebaa52b7717d81/href</a></iframe><p>Dispose pattern gives us a guarantee that the object will be disposed. Because Under the hood using statement is translated to try-finally block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8bb4ad7966d3920ba5bb5977b8905e/href">https://medium.com/media/ba8bb4ad7966d3920ba5bb5977b8905e/href</a></iframe><p>Beginning with C# 8.0, we can use the alternative syntax for ‘using statement’ that doesn’t require braces. It comes with all the same benefits and is cleaner. The same code from the first example takes just 3 lines instead of 7.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd133218df70ef62bfd46e7a6a018205/href">https://medium.com/media/fd133218df70ef62bfd46e7a6a018205/href</a></iframe><p>C# 8.0 also came with IAsyncDisposable. It is used the same way as IDisposable, following the Async pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867ce41670a95473f1a7c1eb1b0fd009/href">https://medium.com/media/867ce41670a95473f1a7c1eb1b0fd009/href</a></iframe><h3>Implementation</h3><p>Implementation requires a parameterless method Dispose, but you should also implement its protected version that accepts bool and private bool variable tracking dispose status.</p><ul><li>public void Dispose()</li><li>protected virtual void Dispose(bool disposing)</li><li>private _disposed</li></ul><p>Dispose should clean up all objects, so Garbage Collector does not have to call Finalize anymore. Therefore we need to suppress it using GC.SuppressFinalize. Suppressing will enhance performance because GC will not put an instance on the finalization queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ce1c8855d4eda5b45151765202d86b/href">https://medium.com/media/06ce1c8855d4eda5b45151765202d86b/href</a></iframe><p>Protected Dispose accepts the ‘bool disposing’ parameter. It indicates the method’s caller. True for a deterministic call from Dispose. False when receiving a non-deterministic call from the finalizer. You, as an implementer, are responsible for the correct value of the disposing parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbbcb0f21731c3dbf3c90aebd3d3d483/href">https://medium.com/media/cbbcb0f21731c3dbf3c90aebd3d3d483/href</a></iframe><p>The method should do nothing if an instance were already disposed. Then if a call comes from public Dispose, we need to free managed resources. In the end, we will release unmanaged resources regardless of the value of the disposing parameter.</p><h4>Cascade Dispose</h4><p>If your class owns a Disposable object as an instance member, it should also implement IDisposable. You are responsible for cleaning your object and all dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed663eb6b1bf2f3c4e2df0e2d2504ce8/href">https://medium.com/media/ed663eb6b1bf2f3c4e2df0e2d2504ce8/href</a></iframe><h4>Finalizer and Safe handles</h4><p>You have to make sure that your object always gets appropriately cleaned up. Unfortunately, you can’t be responsible when someone else consumes your class. It can happen that the coder will forget to dispose of your instance. Fear not, we still have some tools that we can use. Microsoft recommends using Safe Handle. <a href="https://medium.com/@karol.rossa/net-finalizers-3e2a9f85ae4">The finalizer</a> is second option but it is more complex to avoid all pitfalls of releasing resources.</p><p>SafeHandle is an abstract wrapper for operating system handles. It has some default derived classes for the following handles:</p><ul><li>Files (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safefilehandle?view=net-6.0">SafeFileHandle</a> class).</li><li>Memory-mapped files (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safememorymappedfilehandle?view=net-6.0">SafeMemoryMappedFileHandle</a> class).</li><li>Pipes (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safepipehandle?view=net-6.0">SafePipeHandle</a> class).</li><li>Memory views (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safememorymappedviewhandle?view=net-6.0">SafeMemoryMappedViewHandle</a> class).</li><li>Cryptography constructs (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safencrypthandle?view=net-6.0">SafeNCryptHandle</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safencryptkeyhandle?view=net-6.0">SafeNCryptKeyHandle</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safencryptproviderhandle?view=net-6.0">SafeNCryptProviderHandle</a>, and <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safencryptsecrethandle?view=net-6.0">SafeNCryptSecretHandle</a> classes).</li><li>Processes (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safeprocesshandle?view=net-6.0">SafeProcessHandle</a> class).</li><li>Registry keys (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.saferegistryhandle?view=net-6.0">SafeRegistryHandle</a> class).</li><li>Wait handles (the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safewaithandle?view=net-6.0">SafeWaitHandle</a> class).</li></ul><p>In our example, we will use SafeFileHandle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3cea8272ad1d276efd2e38d748b0c0a/href">https://medium.com/media/f3cea8272ad1d276efd2e38d748b0c0a/href</a></iframe><p>Pattern for a class that overrides Finalize is very similar, with the noticeable difference in implementing a finalizer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/694337ce93a801f6cb0bb20ceeab4877/href">https://medium.com/media/694337ce93a801f6cb0bb20ceeab4877/href</a></iframe><h4>Dispose pattern for a derived class</h4><p>Now I will present just the basic example for a derived class. When you want to derive from the Disposable class, you need to override protected Dispose(bool disposing) and call Dispose on the base class. If your class also uses unmanaged resources, you must remember proper pattern implementation like the two examples we have covered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e11931e01e00210ceceef9896ce07e/href">https://medium.com/media/72e11931e01e00210ceceef9896ce07e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce00cdfb6d5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Finalizers]]></title>
            <link>https://medium.com/@karol.rossa/net-finalizers-3e2a9f85ae4?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2a9f85ae4</guid>
            <category><![CDATA[destructor]]></category>
            <category><![CDATA[finalizers]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 16:12:52 GMT</pubDate>
            <atom:updated>2022-06-22T14:24:22.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOOOayt5yBPkBUX7asHQ0g.png" /><figcaption>.NET Finalizers</figcaption></figure><p>Last time we talked about <a href="https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60">Garbage Collection</a><strong>,</strong> it handles memory manipulation for managed code. Unfortunately, you need to release yourself unmanaged resources. Today we will discuss the first option, which is class finalizer. In a future article, I will cover how to use <a href="https://medium.com/@karol.rossa/we-have-already-covered-memory-management-topics-with-garbage-collection-and-implementing-ce00cdfb6d5c">IDisposable</a>.</p><h3>Implementation</h3><p>The Object class has an empty implementation for the Finalize method. In your types, you can’t directly override Finalize because it will yield an error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a333d6565d6ac88f3392ef51b1e729/href">https://medium.com/media/29a333d6565d6ac88f3392ef51b1e729/href</a></iframe><p>From the description, we can see that we have to implement a destructor (finalizer) instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e834845bb99543a9aedd44a228a292/href">https://medium.com/media/85e834845bb99543a9aedd44a228a292/href</a></iframe><p>Finalizer implicitly calls Finalize on the base type. Your implementation will be translated to the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e3d6af0697f82dd29c63168a5c2990/href">https://medium.com/media/57e3d6af0697f82dd29c63168a5c2990/href</a></iframe><p>Because Finalize is implicitly calling the base type Finalize, it ensures that all destructors from your class hierarchy will be executed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df645f17de3ad61af778bb252844b1e/href">https://medium.com/media/3df645f17de3ad61af778bb252844b1e/href</a></iframe><p>In this example, the finalizer will first call Bar’s destructor, then Foo’s.<br>Bar’s destructor <br>Foo’s destructor</p><h3>Remarks</h3><p>We have just covered how to implement a finalizer. Now let us talk about a couple of essential things.</p><ul><li>Finalizers cannot be defined in structs. They are only used with classes.</li><li>A class can only have one finalizer.</li><li>Finalizers cannot be inherited or overloaded.</li><li>Finalizers cannot be called. They are invoked automatically.</li><li>A finalizer does not take modifiers or have parameters.</li></ul><p>It would be best to implement a finalizer only to release unmanaged resources explicitly. If you specify a destructor, only then Garbage Collector will add an instance to the finalization queue. Each item will negatively affect performance.</p><p>Destructor is called only once per instance. In some cases, you can suppress it by calling <a href="https://docs.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize?view=net-5.0">GC.SuppressFinalize</a>. You will mostly use it in Dispose method. .NET 5 (including Core) and later versions don’t call finalizers as part of an application termination. You can’t solely depend on the finalizer to do clean up. It would help if you also used IDisposable. Which we will cover in the following article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2a9f85ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Garbage Collector]]></title>
            <link>https://medium.com/@karol.rossa/garbage-collector-a019b9b0ff60?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/a019b9b0ff60</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 12:53:59 GMT</pubDate>
            <atom:updated>2022-01-19T18:27:26.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="C# .NET — Garbage Collector" src="https://cdn-images-1.medium.com/max/1024/1*SxzuxCAvVcg8DG8F35STdw.png" /><figcaption>Recycle Trash by Roundicons.com from NounProject.com</figcaption></figure><p>The garbage collection process is more complex than you may think. The simplest explanation is that GC manages your application’s allocation and memory release for managed code. Many developers believe the collection process is beyond their control which is not valid.</p><p>Let me show you how GC is working. It will allow you to write your code to achieve the best performance. Also, questions about GC are popular during interviews :)</p><p>The following articles will guide implementing the <a href="https://medium.com/@karol.rossa/we-have-already-covered-memory-management-topics-with-garbage-collection-and-implementing-ce00cdfb6d5c">IDispose</a> interface and <a href="https://medium.com/@karol.rossa/net-finalizers-3e2a9f85ae4">Finalize</a> method.</p><h4>Automatic Process</h4><p>To understand what we can do, let’s first see what is happening automatically. Each of the following conditions can trigger GC:</p><ul><li>The system has low physical memory. OS or host send low memory notification.</li><li>The memory used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.</li><li>When you call the GC.collect method, in most cases, you don’t have to call it because the garbage collector runs continuously. This method is primarily used for unique situations and testing.</li></ul><p>Runtime reserves a contiguous region of address space for the new process. In the .NET world, this is known as Managed Heap. Initially, the pointer is set to the base address. Now our application is ready for allocation. After creating a reference type, GC allocates memory at the base address. The garbage collector allocates memory immediately after the previous object for the next one. The garbage collector releases the memory for references no longer used in the application during collection. GC uses a memory-copying function to compact reachable objects as the last step. (Fig. 1)</p><figure><img alt="Collection process" src="https://cdn-images-1.medium.com/max/1024/1*T7N2A7Axe4Ua9Od1XaO1Gg.png" /></figure><h4>Generations</h4><p>Garbage collector divides objects into generations. We can further split into groups. (Fig. 2)</p><ul><li>short-lived objects</li><li>long-lived objects</li><li>large objects</li></ul><p>Generations 0 and 1, also known as ephemeral, contain short-lived objects. If they live long enough, they will eventually get promoted to generation 2. The first three generations are located on a Small Object Heap (SOH). Large objects are treated differently than the rest. They are placed on a Large Object Heap (LOH), sometimes called generation 3. Generations provide a logical view of the GC heap. The algorithm uses this logic to be more efficient.</p><ul><li>It’s faster to compact the memory for a portion of the managed heap than for the entire managed heap.</li><li>Newer objects have shorter lifetimes, and older ones have longer lifetimes.</li><li>Newer objects tend to be related to each other and accessed by the application simultaneously.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_o2Opq_iUR8dymQjP4PTBw.png" /></figure><h4>Small object heap</h4><p>Garbage collection primarily occurs with the reclamation of short-lived objects. All new objects get allocated in generation 0, and in a well-tuned application, most of them will die there. If an application attempts to create a new object when gen0 is full, the garbage collector performs a collection. At first, only gen0 is examined, and in most cases, this is enough. Objects that survive are promoted to gen1 and ultimately to gen2. Gen1 serves as a buffer between short-lived and long-lived objects.</p><p>Objects that survive the first round of collection tend to have longer lifetimes. The collection process of gen0 does not examine promoted objects because it occurs on the triggered generation and all below.</p><p>Generation 2 contains long-lived objects. A good example is an object with static data in a server application. Objects that survive collection in gen2 are no longer promoted. They only get deallocated once they are no longer reachable by an application.</p><p>Figure 3 illustrates the process of collecting objects in SOH. Survivors Obj 1 and Obj 3 from gen0 form gen1. Then new objects are allocated to gen0. After the following collection, survivors Obj 5 and Obj 7 are moved to gen1, and Obj 1 is moved to long-lived gen2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EE1QDTfCnqqHTR8aBZy3iA.png" /></figure><h4>Large object heap</h4><p>If a new object is larger than 85,000 bytes, it will be allocated on LOH instead of generation 0. We can call a LOH generation 3. It is a separate physical generation that’s logically collected only as part of gen2. Survivors from gen2 and gen3 remain in their respective generations. Objects from LOH by default are not compacted after collection because it would be too expensive. This means that if an object allocated between two others gets collected. It leaves remaining free space. GC can only use this space to allocate smaller objects than the remaining free space.</p><p>Following conditions will trigger LOH collection:</p><ul><li>Allocation exceeds the generation 2 or large object threshold.</li><li>You call the GC.Collect method.</li><li>The system is in a low memory situation.</li></ul><h4>LOH performance</h4><p>Allocating objects on LOH can have an impact on performance. CLR must clear memory for every new object. Collection can be triggered by either gen 2 or LOH hitting the threshold. You have to be cautious because large object allocation can trigger GC and if your gen 2 heap is large, then checking it can affect garbage collection time. Also, if you have many objects in SOH, it can trigger the collection of gen 2 and, by implication, LOH. If your application takes too much time for GC, this is worth checking out.</p><p>LOH, in most cases, contains arrays. If an array contains reference-rich objects, it incurs a cost that is not present if elements are not reference-rich. During garbage collection, each reference needs to be checked. GC does not need to go through the elements in a reference-free array at all. If you need to work with many large arrays, it is best to utilize an <a href="https://docs.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=net-6.0">array pool</a>.</p><h4>Workstation or Server Garbage Collection</h4><p>The garbage collector is self-tuning and works well in many scenarios. Now we will discuss the significant settings available to you. You can choose between Workstation and Server garbage collection. Both can be concurrent or background, which is the default option. The workstation was designed for client applications and is the default option for standalone apps. The server garbage collector is intended for server applications that need high throughput and scalability. A host determines the default GC flavor for hosted apps (ex. ASP.NET).</p><p>Here are some key differences between both flavors:</p><p><strong>Workstation GC</strong></p><ul><li>The collection occurs on the user thread that triggered it and remains the same priority. They typically run at normal priority, so GC must compete with other threads for CPU time.</li><li>Workstation is always used on computers with only one processor, regardless of configuration.</li></ul><p><strong>Serve GC</strong></p><ul><li>The collection occurs on multiple threads running at the highest priority level.</li><li>A heap and dedicated thread are provided for each CPU, and they are collected simultaneously. All heaps can be accessed by user code. Objects on different heaps can refer to each other.</li><li>Because of parallelization Server GC, is faster than Workstation GC on the same heap size.</li><li>Server garbage collection tends to have more significant size segments. Nevertheless, size is implementation-specific and is subject to change. You should not make assumptions about the segment size.</li><li>If you are running hundreds of instances of an application, consider using workstation garbage collection with a background setting.</li></ul><h4>Background GC</h4><p>Background collection applies only to generation 2 and is enabled by default. It is performed on one or more dedicated threads. Ephemeral generations (0 and 1) collection occurs as needed alongside. Foreground collection (ephemeral) suspends all managed threads.</p><p>There are two significant differences between server and workstation background garbage collection. The workstation uses only one dedicated thread, whereas the server can use multiple threads. This number usually matches the number of physical processors. Also, server GC threads do not time out.</p><p>You can also enable concurrent GC, allowing threads to run concurrently with a dedicated garbage collection thread. This does not affect generations 0 and 1 as they are always non-concurrent. Concurrent garbage collection enables interactive applications to be more responsive by minimizing pauses for collection.</p><h4>Configuration</h4><p>Large object heap can be compacted automatically when the hard memory limit is set.</p><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector#heap-limit">GCHeapHardLimit</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector#heap-limit-percent">GCHeapHardLimitPercent</a></li></ul><p>Additionally, you can compact LOH on-demand using property <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gcsettings.largeobjectheapcompactionmode?view=net-6.0">GCSettings.LargeObjectHeapCompactionMode</a>. Here you can find information on setting the type of GC (workstation/server) <a href="https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector#flavors-of-garbage-collection">GC Flavors</a>. You can always disable <a href="https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector#background-gc">background GC</a> if this is desirable in your case. Last but not least, you can enable <a href="https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcconcurrent-element">concurrent GC</a>. There are additional <a href="https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector">settings</a> like heaps count and size that you can tune for best performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a019b9b0ff60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next step in programmer’s career]]></title>
            <link>https://medium.com/@karol.rossa/next-step-in-programmers-career-a2fe5e3489fd?source=rss-9f0a071996------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2fe5e3489fd</guid>
            <category><![CDATA[social-engineering]]></category>
            <category><![CDATA[social-engagement]]></category>
            <category><![CDATA[human-relations]]></category>
            <dc:creator><![CDATA[Karol Rossa]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 15:50:11 GMT</pubDate>
            <atom:updated>2021-10-05T15:50:11.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to work with people</h3><p>Young engineers become developers to solve logical problems and to write code. At some point gaining more technical knowledge is not enough. They would like to explore other opportunities in the tech world. Aim at a leading role in your team or reach higher for the CTO position.</p><p>At that point, nothing they have done could prepare for this. The ultimate challenge of engineering humans instead of computers :)</p><p>If this is something that interests you, look no more. Dale Carnegie wrote a helpful book. With the self-explanatory title “How to win friends and influence people”.</p><p>I recommend reading it but for now, let me extract its essence.</p><h3>How to make people like you.</h3><blockquote>“Become genuinely interested in other people.”</blockquote><p>If people will feel that you are. They will open up to you and share their thoughts. It will bring you closer together. You will be welcome anywhere.</p><blockquote>“Smile”</blockquote><p>It puts people in a better mood. It is a messenger of your goodwill.</p><blockquote>“Remember that a person’s name is to that person the sweetest and most important sound in any language.”</blockquote><p>If you can remember the name of people that you have just met, they will appreciate it. The name makes people unique. Sets them apart from everyone else.</p><blockquote>“Be a good listener. Encourage others to talk about themselves.”</blockquote><p>If you feel uncomfortable with small talk, use this trick. This is the easiest way to become a good conversationalist.</p><blockquote>“Talk in terms of the other person’s interests.”</blockquote><p>It will always pay off for both parties. Private conversion about interests can turn into a business opportunity.</p><blockquote>“Make the other person feel important — and do it sincerely.”</blockquote><p>People like to feel important. If you can do it they will instantly like you. If you can put trust into others they will repay with loyalty and hard work.</p><h3>How to win people to your way of thinking.</h3><p>In the first place let’s avoid making enemies. Begin in a friendly way and relieve tension. Be polite and respectful of others’ opinions. Be sympathetic with their ideas and desires. That is what everybody wants. Even if they are wrong don’t say it. Try honestly to see their point of view. Then during peaceful conversation let the other person feel that your idea is theirs. But if you are wrong, admit it quickly and emphatically. You want to focus on what is important not to protect your pride. When you are explaining something try to make the other person say ‘yes, yes’ immediately. It will set their mind in the right direction.</p><p>Remember one thing. You can’t win an argument. If you lose it, you lose it. If you win your partner feels terrible. He will resent your victory.</p><h3>Final thoughts</h3><p>From this book, you will learn how to become a leader. How to change people without giving offense or arousing resentment. It will make your life and the people around you easier. A lot of topics mentioned seem obvious but it is hard to live by those rules. The author shows a lot of examples from the lives of great people.</p><p>If you managed to this part of the text I strongly recommend reading the book.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2fe5e3489fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>