<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Alex Lazarev's blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/alazarev/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/alazarev/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 03:47:44 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Disposable, Finalizers, and HttpClient</title>
      <link>https://docs.microsoft.com/archive/blogs/alazarev/disposable-finalizers-and-httpclient</link>
      <pubDate>Fri, 29 Dec 2017 05:52:19 GMT</pubDate>
      <dc:creator><![CDATA[Alex Lazarev]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/alazarev/?p=85</guid>
      <description><![CDATA[In this essay I wanted to share some investigation that I've done on the topic of C# Disposal,...]]></description>
      <content:encoded><![CDATA[In this essay I wanted to share some investigation that I've done on the topic of C# Disposal, Finalizers, and how it's related to the correct usage of HttpClient.

<b>Abstract</b>

We start with some general introduction of disposal and finalization in C#. I was interested, whether disposal is required, is disposal happening during garbage collection, and whether the unmanaged resources are released when the process is terminated, and by whom. Then we proceed to investigate the correct usages of HttpClient in regards to disposal.

Let's start one by one.

<b>Finalizers</b>

First, we are going to check if the finalizers are run when the garbage is collected, and when the process is terminated.

<pre>
    class Program
    {
        static A a = new A() { a = "a" };

        static void Main(string[] args)
        {
            Foo();
            Console.WriteLine("Starting to collect");
            GC.Collect();
            Console.WriteLine("Finished collecting");
            Console.ReadLine();
            Console.WriteLine("Ending process");
        }

        static void Foo()
        {
            Console.WriteLine("Starting Foo");
            A b = new A() { a = "b" };
            Console.WriteLine("Finishing Foo");
        }
    }

    class A
    {
        public string a;

        ~A()
        {
            Console.WriteLine("Finalize " + a);
        }
    }
</pre>

That's the output we get:
<pre>
Starting Foo
Finishing Foo
Starting to collect
Finished collecting
Finalize b

Ending process
Finalize a
</pre>
So, it looks like, if the process is terminating correctly, finalizers are run by the collector. Which is actually different from the Dispose method. Let's add Dispose method:
<pre>
    class A : IDisposable
    {
        public string a;

        public void Dispose()
        {
            Console.WriteLine("Disposing " + a);
        }

        ~A()
        {
            Console.WriteLine("Finalize " + a);
        }
    }
</pre>
As you can see, the output will be absolutely the same. So it means that unless you run Dispose manually, or run it from the finalizer, it won't be run by the garbage collector. So if you have any unmanaged resources that need to be taken care of, you definitely should pay attention.

Now let's see what happens if the process terminates incorrectly, by sending it the terminate signal, using, for example, ProcessHacker [6]:
<pre>
Starting Foo
Finishing Foo
Starting to collect
Finished collecting
Finalize b
</pre>

So you can see that the finalizer wasn't called. But we are not sure, what if it was called when the console wasn't available anymore. Let's modify the code:
<pre>
        ~A()
        {
            Console.WriteLine("Finalize " + a);
            if (a == "a")
            {
                File.WriteAllText("bar", "bar");
            }
        }
</pre>
Turns out, still no luck. And [7] supports this finding.
<blockquote>No "user mode" code in the process has a chance to run when a process is terminated.</blockquote>
Moreover, any finalizer code that is ever run is limited by time [12]:
<blockquote>"[When a process is gracefully terminating], each Finalize method is given approximately 2 seconds to return. If a Finalize method doesn't return within 2 seconds, the CLR just kills the process - no more Finalize methods are called. Also, if it takes more than 40 seconds to call all objects' Finalize methods, then again, the CLR just kills the process. Note: These timeout values were correct at the time I wrote this text, but Microsoft might change them in the future."
- Jeffrey Richter, Applied Microsoft .NET Framework Programming, pg 467; and CLR via C#, 2nd ed, pg 478
</blockquote>

<b>Disposal</b>

Disposal is said to be required when there are some unmanaged resources that are needed to be released. Suppose, you are creating a file:
<pre>
            var f = File.OpenWrite("foo.txt");
            Console.WriteLine(f.Handle);
            Console.ReadLine();
</pre>
f.Handle will contain the OS handle for the open file. You can look it up using handle [5]:
<pre>
FileCreate1.exe    pid: 6332   type: File            D4: foo.txt
</pre>
Suppose we send terminate signal to the process, to make sure that even the finalizers won't run, like we found out above. Let's see if the handle will still be active.
If you run the code, kill the process, and look for the handle using
<pre>
handle foo
</pre>
you'll get no dice:
<pre>
No matching handles found.
</pre>
So the OS is indeed collecting the handles on the process termination. You can also find this out, because you will eventually get the same handle ID.

Also, we should take notice, that if you plan to derive from your class, and you run your Dispose method from both the finalizer, and manually, take care that you include some checks, and don't crash when you run the Dispose from the finalizer, after you had already run it from the main code manually.

So, we can summarize:
<ul>
<li>Finalizers are run on garbage collection</li>
<li>Dispose method is not run automatically, you need to run it manually and/or from the finalizer, if you need to dispose of unmanaged resources</li>
<li>Finalizers are not run on process termination</li>
<li>Unmanaged resources are collected by OS on process termination</li>
<li>Take care of double disposal, especially when using derived classes</li>
</ul>

The conclusion would be:
<ul>
<li>You need to care about manually calling Dispose and disposing unmanaged objects if you recreate your objects at runtime</li>
<li>You don't need to care about collecting unmanaged objects on process termination, as OS will take care of it</li>
<li>Take care of double disposal, especially when using derived classes</li>
</ul>

Now let's look at the main topic.

<b>HttpClient</b>

Standard by-the-book usage is supposed to be like this, given that it implements IDisposable, and hence you can use <b>using</b> to call Dispose automatically:
<pre>
                using (var client = new HttpClient())
                {
                    var result = await client.GetAsync("https://example.com/");
                }
</pre>
Suppose you're creating a bunch of requests:
<pre>
            for (int i = 0; i &lt; 10; i++)
            {
                using (var client = new HttpClient())
                {
                    var result = await client.GetAsync(&quot;https://example.com/&quot;);
                    Console.WriteLine(result.StatusCode);
                }
            }
</pre>
The problem with this approach is that each client will create a socket that will survive even after the application closes. This is the output of <b>netstat</b> command <i>after</i> the process has terminated [1]:
<pre>
  TCP    192.168.1.6:13996      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:13997      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:13998      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:13999      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14000      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14001      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14002      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14003      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14004      93.184.216.34:http     TIME_WAIT
  TCP    192.168.1.6:14005      93.184.216.34:http     TIME_WAIT
</pre>
So, as you can imagine, if you are creating a lot of requests, you're going to create a hell of a lot of sockets, even though you're disposing it supposedly properly.

According to [2], the reason for this behavior is not something to do with C# or disposing, but with the OS behavior in regards to sockets.

<blockquote>They are in the TIME_WAIT state which means that the connection has been closed on one side (ours) but we’re still waiting to see if any additional packets come in on it because they might have been delayed on the network somewhere.</blockquote>

Here's the diagram:

<img src="https://www4.cs.fau.de/Projects/JX/Projects/TCP/tcpstate.gif" />

So, according to [3], or many other community resources, the general recommendation is that you should use one global instance of HttpClient, which is thread-safe, and don't dispose it at all. Thread safety is documented in [4]:
<pre>
The following methods are thread safe:

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync</pre>

Also stated in MSDN:

<blockquote>HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.</blockquote>

According to our findings above, this should be fine, as if we don't recreate the object at runtime, the OS will collect any unmanaged objects upon project termination, so disposal is not necessary.

It's also worth noting, that, suppose if you're writing a command line tool, not an online service, that you should take notice at this behavior. If you just follow by-the-book practice, your tool can hog up the system up to no good. Take a look at what <b>curl</b> tool does, for example: it reuses sticky connections between the runs for this purpose.

I was interested to see the source of HttpClient to see what they actually do in the finalizer and/or Dispose method. Gladly, it's available on github [8]:
<pre>
        private CancellationTokenSource _pendingRequestsCts;

        protected override void Dispose(bool disposing)
        {            
            if (disposing &amp;&amp; !_disposed)
            {
                _disposed = true;

                // Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
                // the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
                // a new CTS. We don't want a new CTS in this case.
                _pendingRequestsCts.Cancel();
                _pendingRequestsCts.Dispose();
            }

            base.Dispose(disposing);
        }

        public Task SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            CheckDisposed();
            CheckRequestMessage(request);

            SetOperationStarted();
            PrepareRequestMessage(request);
            // PrepareRequestMessage will resolve the request address against the base address.

            // We need a CancellationTokenSource to use with the request.  We always have the global
            // _pendingRequestsCts to use, plus we may have a token provided by the caller, and we may
            // have a timeout.  If we have a timeout or a caller-provided token, we need to create a new
            // CTS (we can't, for example, timeout the pending requests CTS, as that could cancel other
            // unrelated operations).  Otherwise, we can use the pending requests CTS directly.
            CancellationTokenSource cts;
            bool disposeCts;
            bool hasTimeout = _timeout != s_infiniteTimeout;
            if (hasTimeout || cancellationToken.CanBeCanceled)
            {
                disposeCts = true;
                cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token);
                if (hasTimeout)
                {
                    cts.CancelAfter(_timeout);
                }
            }
            else
            {
                disposeCts = false;
                cts = _pendingRequestsCts;
            }

            // Initiate the send
            Task sendTask = base.SendAsync(request, cts.Token);
            return completionOption == HttpCompletionOption.ResponseContentRead ?
                FinishSendAsyncBuffered(sendTask, request, cts, disposeCts) :
                FinishSendAsyncUnbuffered(sendTask, request, cts, disposeCts);
        }
</pre>

Ok, not much going on here except sending cancellations to the pending requests. Let's look at the base class [9]:
<pre>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; !_disposed)
            {
                _disposed = true;

                if (_disposeHandler)
                {
                    _handler.Dispose();
                }
            }
        }
</pre>

Nothing except calling HttpMessageHandler's Dispose. Also, take a notice, none of the classes include a finalizer. So, according to our investigation above, they won't be disposed by the garbage collector, if you don't run Dispose manually from your own code. I wonder why, actually?

Now let's look at HttpMessageHandler [10]: it's an abstract class. But, by default, HttpClient uses HttpClientHandler as a handler. Its source is not available on github except for Mono implementation, but we can assume it should be fairly similar [13].

The Mono implementation shows some of the HttpClientHandler:
<pre>
		static long groupCounter;

		public HttpClientHandler ()
		{
			allowAutoRedirect = true;
			maxAutomaticRedirections = 50;
			maxRequestContentBufferSize = int.MaxValue;
			useCookies = true;
			useProxy = true;
			connectionGroupName = "HttpClientHandler" + Interlocked.Increment (ref groupCounter);
		}

		protected override void Dispose (bool disposing)
		{
			if (disposing &amp;&amp; !disposed) {
				Volatile.Write (ref disposed, true);
				ServicePointManager.CloseConnectionGroup (connectionGroupName);
			}

			base.Dispose (disposing);
		}

		internal virtual HttpWebRequest CreateWebRequest (HttpRequestMessage request)
		{
			var wr = new HttpWebRequest (request.RequestUri);
			wr.ThrowOnError = false;
			wr.AllowWriteStreamBuffering = false;

			wr.ConnectionGroupName = connectionGroupName;

...............................................
		}
</pre>

So, we can see, that the recommended way to use HttpClient is to avoid recreating it, but rather use one single global instance, and the connections will be sticky, and kept in ServicePointManager. There's one problem, however, with global HttpClient, and it's that DNS changes are not honored [11], because it, duh, keeps a sticky connection, obviously, for perf reasons.

The classic and currently industry standard solution is to set the timeout:
<pre>
var sp = ServicePointManager.FindServicePoint(new Uri("https://example.com"));
sp.ConnectionLeaseTimeout = 60*1000;
</pre>

So, we can summarize:

<ul>
<li>HttpClient is not supposed to be recreated at runtime, but rather one single global object is to be constructed and used</li>
<li>HttpClient is mostly thread safe</li>
<li>Creating lots of HttpClient objects will create lots of sockets, which is rather expensive</li>
<li>Disposing global HttpClient is not needed</li>
<li>To solve sticky connection issue, use a timeout</li>
</ul>

Now we know a lot of new stuff, let's go code some new services!

<b>References</b>
<ol>
<li>https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/</li>
<li>https://www4.cs.fau.de/Projects/JX/Projects/TCP/tcpstate.html</li>
<li>https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed</li>
<li>https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx</li>
<li>https://docs.microsoft.com/en-us/sysinternals/downloads/handle</li>
<li>https://processhacker.sourceforge.net/</li>
<li>https://social.msdn.microsoft.com/Forums/vstudio/en-US/4f62bca8-78d6-4848-97e3-355210dc61e9/c-destructorfinalize-method-on-process-killed?forum=clr</li>
<li>https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs</li>
<li>https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs</li>
<li>https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs</li>
<li>https://byterot.blogspot.com/2016/07/singleton-httpclient-dns.html</li>
<li>https://blog.stephencleary.com/2009/08/finalizers-at-process-exit.html</li>
<li>https://github.com/mono/mono/blob/master/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs</li>
</ol>

]]></content:encoded>
    </item>
    <item>
      <title>Access to modified closure in Resharper/C#</title>
      <link>https://docs.microsoft.com/archive/blogs/alazarev/access-to-modified-closure-in-resharperc</link>
      <pubDate>Sun, 21 May 2017 02:17:07 GMT</pubDate>
      <dc:creator><![CDATA[Alex Lazarev]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/alazarev/?p=75</guid>
      <description><![CDATA[We all know that Resharper complains about modified closure when you write something like this:...]]></description>
      <content:encoded><![CDATA[We all know that Resharper complains about modified closure when you write something like this:
<pre>
        static void Main(string[] args)
        {
            Action action = () =&gt; Console.WriteLine(0);
            for (int i = 0; i &lt; 10; i++)
            {
                if (i == 1)
                    action = () =&gt; Console.WriteLine(i);
            }

            action();
        }
</pre>
But it stops, once you write it this way:
<pre>
        static void Main(string[] args)
        {
            Action action = () =&gt; Console.WriteLine(0);
            for (int i = 0; i &lt; 10; i++)
            {
                int copy = i;
                if (i == 1)
                    action = () =&gt; Console.WriteLine(copy);
            }

            action();
        }
</pre>
The difference is that the result of the first code is 10, but the second is 1. We know that it somehow has to do with closures and variable binding, and we just should write it the second way. But what’s going on under the hood?
Let’s use Reflector to see:
<pre>
	internal class Program
	{
		private static void Main(string[] args)
		{
			Action action = (&lt;&gt;c.&lt;&gt;9__0_0 != null) ?
				&lt;&gt;c.&lt;&gt;9__0_0 :
				(&lt;&gt;c.&lt;&gt;9__0_0 = new Action(this.&lt;Main&gt;b__0_0));
			&lt;&gt;c__DisplayClass0_0 class_ = new &lt;&gt;c__DisplayClass0_0();
			class_.i = 0;
			while (class_.i &lt; 10)
			{
				if (class_.i == 1)
				{
					action = new Action(class_.&lt;Main&gt;b__1);
				}
				int i = class_.i;
				class_.i = i + 1;
			}
			action();
		}

		[Serializable, CompilerGenerated]
		private sealed class &lt;&gt;c
		{
			public static readonly Program.&lt;&gt;c &lt;&gt;9 = new Program.&lt;&gt;c();
			public static Action &lt;&gt;9__0_0;

			internal void &lt;Main&gt;b__0_0()
			{
				Console.WriteLine(0);
			}
		}
	}

	[CompilerGenerated]
	private sealed class &lt;&gt;c__DisplayClass0_0
	{
		public int i;

		internal void &lt;Main&gt;b__1()
		{
			Console.WriteLine(this.i);
		}
	}
</pre>
Now we can see, that once we used a free variable in a closure, it’s no longer free, and it has been bound since that place during the compilation. It’s even easier to think that the variable now belongs to the closure, and just happen to be used outside, not vice versa.
As the variable is now bound, we can see that it keeps incrementing it inside the closure as the loop goes on. Hence the result. So the closure gets created one time before the loop, and persists the whole way.

Now what about the second approach:
<pre>
        private static void Main(string[] args)
        {
            Action action = (&lt;&gt;c.&lt;&gt;9__0_0 != null) ?
				&lt;&gt;c.&lt;&gt;9__0_0 :
				(&lt;&gt;c.&lt;&gt;9__0_0 = new Action(this.&lt;Main&gt;b__0_0));
            for (int i = 0; i &lt; 10; i++)
            {
                &lt;&gt;c__DisplayClass0_0 class_ = new &lt;&gt;c__DisplayClass0_0();
                class_.copy = i;
                if (i == 1)
                {
                    action = new Action(class_.&lt;Main&gt;b__1);
                }
            }
            action();
        }

        [Serializable, CompilerGenerated]
        private sealed class &lt;&gt;c
        {
            public static readonly Program.&lt;&gt;c &lt;&gt;9 = new Program.&lt;&gt;c();
            public static Action &lt;&gt;9__0_0;

            internal void &lt;Main&gt;b__0_0()
            {
                Console.WriteLine(0);
            }
        }
</pre>
Ok, now it’s completely different. The original index variable is now free, and the closure is constructed on each loop iteration, and the copy of the index is bound to the closure. So, in total, we create 10 closures, and collect 9 of them, and only one of them persists after the loop. So, in terms of garbage collection, it doesn’t look like a very efficient code, as it creates much more garbage.

What if we don’t bind the closure to anything, will we get the same number of collections? Let’s see:
<pre>
	private static void Main(string[] args)
	{
		Action action = (&lt;&gt;c.&lt;&gt;9__0_0 != null) ?
			&lt;&gt;c.&lt;&gt;9__0_0 :
			(&lt;&gt;c.&lt;&gt;9__0_0 = new Action(this.&lt;Main&gt;b__0_0));
		for (int i = 0; i &lt; 10; i++)
		{
			if (i == 1)
			{
				action = (&lt;&gt;c.&lt;&gt;9__0_1 != null) ?
					&lt;&gt;c.&lt;&gt;9__0_1 :
					(&lt;&gt;c.&lt;&gt;9__0_1 = new Action(this.&lt;Main&gt;b__0_1));
			}
		}
		action();
	}
</pre>
And we can see that no, and actually no closure class will be constructed at all.

Let's get back and see if optimizer does anything with it:
<pre>
        private static void Main(string[] args)
        {
            Action action = (&lt;&gt;c.&lt;&gt;9__0_0 != null) ?
				&lt;&gt;c.&lt;&gt;9__0_0 :
				(&lt;&gt;c.&lt;&gt;9__0_0 = new Action(this.&lt;Main&gt;b__0_0));
            for (int i = 0; i &lt; 10; i++)
            {
                &lt;&gt;c__DisplayClass0_0 class_ = new &lt;&gt;c__DisplayClass0_0();
                class_.copy = i;
                if (i == 1)
                {
                    action = new Action(class_.&lt;Main&gt;b__1);
                }
            }
            action();
        }
</pre>
Looks like not much. Let’s look at the IL (using dotPeek):
<pre>
    // IL_0022: br.s         IL_0046
    // // start of loop, entry point: IL_0046
    // IL_0024: newobj       instance void ModifiedClosure1.Program/'&lt;&gt;c__DisplayClass0_0'::.ctor()
      // IL_0029: stloc.2      // 'cDisplayClass00 [Range(Instruction(IL_0029 stloc.2)-Instruction(IL_0035 ldloc.2))]'
      // IL_002a: ldloc.2      // 'cDisplayClass00 [Range(Instruction(IL_0029 stloc.2)-Instruction(IL_0035 ldloc.2))]'
      // IL_002b: ldloc.1      // 'index [Range(Instruction(IL_0021 stloc.1)-Instruction(IL_0046 ldloc.1))]'
      // IL_002c: stfld        int32 ModifiedClosure1.Program/'&lt;&gt;c__DisplayClass0_0'::copy
      // IL_0031: ldloc.1      // 'index [Range(Instruction(IL_0021 stloc.1)-Instruction(IL_0046 ldloc.1))]'
      // IL_0032: ldc.i4.1     
      // IL_0033: bne.un.s     IL_0042
      // IL_0035: ldloc.2      // 'cDisplayClass00 [Range(Instruction(IL_0029 stloc.2)-Instruction(IL_0035 ldloc.2))]'
      // IL_0036: ldftn        instance void ModifiedClosure1.Program/'&lt;&gt;c__DisplayClass0_0'::'&lt;Main&gt;b__1'()
      // IL_003c: newobj       instance void [mscorlib]System.Action::.ctor(object, native int)
      // IL_0041: stloc.0      // 'action [Range(Instruction(IL_001f stloc.0)-Instruction(IL_004b ldloc.0))]'
      // IL_0042: ldloc.1      // 'index [Range(Instruction(IL_0021 stloc.1)-Instruction(IL_0046 ldloc.1))]'
      // IL_0043: ldc.i4.1     
      // IL_0044: add          
      // IL_0045: stloc.1      // 'index [Range(Instruction(IL_0021 stloc.1)-Instruction(IL_0046 ldloc.1))]'
      // IL_0046: ldloc.1      // 'index [Range(Instruction(IL_0021 stloc.1)-Instruction(IL_0046 ldloc.1))]'
      // IL_0047: ldc.i4.s     10 // 0x0a
      // IL_0049: blt.s        IL_0024
      // // end of loop
</pre>
So yeah, looks like it’s still inside the loop. And it makes sense, if the optimizer couldn’t prove that the object creation is free of any side effects.
C# currently has no way of specifying purity. It has a [Pure] attribute, but it’s not really enforced:

From <a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute.aspx" target="_blank">https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute.aspx</a>:

<blockquote>Methods and types that are marked with this attribute can be used in calls to System.Diagnostics.Contracts.Contract methods. Pure methods do not make any visible state changes. This attribute is not enforced by the current analysis tools; you should use this attribute only if you are sure that the methods are pure.</blockquote>

Getting back to the original problem, however, you have to be careful, as Resharper won't catch everything. Let's see what happens if we use reference type as an "index":

<pre>
    class AdvancedInt
    {
        public int i = 0;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Action action = () =&gt; Console.WriteLine(0);
            AdvancedInt i = new AdvancedInt();
            while (i.i &lt; 10)
            {
                AdvancedInt copy = i;
                if (i.i == 1)
                    action = () =&gt; Console.WriteLine(copy.i);

                ++i.i;
            }

            action();
        }
    }
</pre>

The result will be 10 again, and Resharper won't complain. It's easy to see why, because the copy is only a reference. We don't even need Reflector to see this.

So we can conclude several facts:
<ul>
<li>closure variables are bound at their first use, and closure class is created at that point</li>
<li>using closures with bound variables inside long loops creates lots of garbage collection</li>
<li>don't rely on Resharper catching all closure binding errors</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Fun with pure C# and monads</title>
      <link>https://docs.microsoft.com/archive/blogs/alazarev/fun-with-pure-c-and-monads</link>
      <pubDate>Sat, 20 May 2017 06:05:09 GMT</pubDate>
      <dc:creator><![CDATA[Alex Lazarev]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/alazarev/?p=66</guid>
      <description><![CDATA[We are all fascinated by pure languages like Haskell, but unfortunately have to code in C#. We could...]]></description>
      <content:encoded><![CDATA[We are all fascinated by pure languages like Haskell, but unfortunately have to code in C#. We could complain to our neighbor all day, but instead, what if we could also do something really pure in C#. Actually we can, it&rsquo;s called LINQ:
<pre>
            var sum = from a in new[] { 1 }
                from b in new[] { 2 }
                from c in new[] { 3 }
                where a + b &gt; c
                select a + b + c;
</pre>
Don&rsquo;t know about you, looks pretty darn pure to me. No side effects given. However, we can&rsquo;t do much without side effects in the real world. In Haskell, as a pure language, we have to encapsulate all side effects into monads.
What if we wanted to write pure in C#, but also needed side effects. C# supports side effects, but only in imperative style:
<pre>
            Console.WriteLine(sum);
</pre>
Seems legit. But to us, functional people, not much fun. What if we could write pure, but still have side effects, whenever needed. Luckily, we can define a fancy monad to help us:
<pre>
        public delegate T IO&lt;out T&gt;();

        public static IO&lt;R&gt; SelectMany&lt;S, C, R&gt;(this IO&lt;S&gt; A, Func&lt;S, IO&lt;C&gt;&gt; foo, Func&lt;S, C, R&gt; bar)
        {
            var a = A();
            var B = foo(a);
            var b = B();
            var c = bar(a, b);
            return () =&gt; c;
        }

        public static IO&lt;T&gt; Combine&lt;T&gt;(IO&lt;T&gt; a, Action b)
        {
            return new Func&lt;IO&lt;T&gt;, IO&lt;T&gt;&gt;(x =&gt; { b(); return x; })(a);
        }

        public static IO&lt;T&gt; Where&lt;T&gt;(this IO&lt;T&gt; t, Func&lt;T, bool&gt; foo)
        {
            return () =&gt; (foo(t()) ? t : Combine(t, () =&gt; { Console.WriteLine(&quot;We screwed up!&quot;); }))();
        }

        public static IO&lt;R&gt; Select&lt;S, R&gt;(this IO&lt;S&gt; s, Func&lt;S, R&gt; foo)
        {
            return () =&gt; new Func&lt;IO&lt;S&gt;, R&gt;(x =&gt; foo(x()))(s);
        }
</pre>
Now let&rsquo;s do some serious pure coding with side effects:
<pre>
            var A = new IO&lt;int&gt;(() =&gt; { Console.WriteLine(&quot;A&quot;); return 6; });
            var B = new IO&lt;int&gt;(() =&gt; { Console.WriteLine(&quot;B&quot;); return 7; });
            var C = new IO&lt;int&gt;(() =&gt; { Console.WriteLine(&quot;C&quot;); return 10; });

            var sum =
                from a in A
                from b in B
                from c in C
                let x = 10
                where a &gt; b
                select a + b + c + x;
</pre>
Now that looks real fun to me all right.

Henceforth, you can be really sneaky, and hide side effects in places where your coworker least expects them: in pure LINQ expressions. Happy debugging!
]]></content:encoded>
    </item>
    <item>
      <title>Fun with ConfigureAwait, and deadlocks in ASP.NET</title>
      <link>https://docs.microsoft.com/archive/blogs/alazarev/fun-with-configureawait-and-deadlocks-in-asp-net</link>
      <pubDate>Sat, 20 May 2017 05:54:23 GMT</pubDate>
      <dc:creator><![CDATA[Alex Lazarev]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/alazarev/?p=56</guid>
      <description><![CDATA[Coworker and I investigated a cool issue with deadlocks we found some time ago when porting some...]]></description>
      <content:encoded><![CDATA[Coworker and I investigated a cool issue with deadlocks we found some time ago when porting some async code from one service to another. The difference was that one was written with async/await down to the controller, and the other follows legacy Task.Run model. When trying to code like this we encountered a deadlock:
<pre>    public class HomeController : Controller
    {
        public static async Task GetJsonAsync(Uri uri)
        {
            using (var client = new HttpClient())
            {
                var jsonString = await client.GetStringAsync(uri); 
                return jsonString;
            }
        }

        public ActionResult Index()
        {
            var jsonTask = GetJsonAsync(new Uri("https://example.com"));

            ViewBag.Title = jsonTask.Result.ToString();       // deadlock here!!

            return View();
        }
    }
</pre>
We were trying to figure it out, and it worked with a different approach:
<pre>    public class HomeController : Controller
    {
        public static async Task GetJsonAsync(Uri uri)
        {
            using (var client = new HttpClient())
            {
                var jsonString = await client.GetStringAsync(uri);
                return jsonString;
            }
        }

        public ActionResult Index()
        {
            var jsonTask = Task.Run(() =&gt; GetJsonAsync(new Uri("https://example.com")));

            ViewBag.Title = jsonTask.Result.ToString();       // works fine!!

            return View();
        }
    }
</pre>
I remembered it could have to be something with synchronization context in ASP.NET, but didn’t quite remember what exactly. I googled up a bit, and found this explanation:

<a target="_blank" href="https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html">https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html</a>

So, according to it, ASP.NET has a specialized sync context, that only one thread can have. And if you don’t use .ConfigureAwait(false), it tries to restore old context, which belongs to the main thread that is blocked by .Result, hence deadlock. In the second example, the func is run on a different thread, and doesn’t need ASP.NET context, which is also blocked, but it’s OK now.

With ConfigureAwait it also works, without a thread:
<pre>        public static async Task GetJsonAsync(Uri uri)
        {
            using (var client = new HttpClient())
            {
                var jsonString = await client.GetStringAsync(uri).ConfigureAwait(false);
                return jsonString;
            }
        }

        public ActionResult Index()
        {
            var jsonTask = GetJsonAsync(new Uri("https://example.com"));

            ViewBag.Title = jsonTask.Result.ToString();       // works fine!!

            return View();
        }
</pre>
What on earth exactly is a sync context, and why ASP.NET behaves this way? This looks like a good intro:

<a target="_blank" href="https://msdn.microsoft.com/en-us/magazine/gg598924.aspx">https://msdn.microsoft.com/en-us/magazine/gg598924.aspx</a>]]></content:encoded>
    </item>
  </channel>
</rss>