Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Last active January 19, 2019 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfowl/94d1b7d60ad544289b5f60df4c8a6520 to your computer and use it in GitHub Desktop.
Save davidfowl/94d1b7d60ad544289b5f60df4c8a6520 to your computer and use it in GitHub Desktop.
Leaking tasks
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp19
{
class Program
{
private static Dictionary<string, Task<string>> _cache = new Dictionary<string, Task<string>>();
static async Task Main(string[] args)
{
await MakeRequest("/foo");
await MakeRequest("/bar");
await MakeRequest("/baz");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
private static async Task MakeRequest(string path)
{
HttpContext.Current = new HttpContext();
await Run(path);
HttpContext.Current = null;
}
private static Task Run(string path)
{
if (!_cache.TryGetValue(path, out var task))
{
task = ComputeAsyncThing(path);
_cache[path] = task;
}
return task;
}
private static async Task<string> ComputeAsyncThing(string path)
{
await Task.Delay(1000);
return "Computed " + path;
}
}
public class HttpContext
{
private static AsyncLocal<HttpContext> _current = new AsyncLocal<HttpContext>();
public static HttpContext Current
{
get => _current.Value;
set => _current.Value = value;
}
public object MyProperty { get; set; } = new object();
}
}
@mitchellm44
Copy link

WIth .net core SDK 2.2 - when I compile this code it gave me an error - something about not C#7.1 (dotnet run was my approach).
I had to change the main entry to get the code to run

    static void Main(string[] args)
    {
        MainTask(args).GetAwaiter().GetResult();
    }

    static async Task MainTask(string[] args).... 

Then I used Visual Studio to see the memory leak.
taking memory snapshots. - so was this to prove something on the compiler side?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment