Last active
January 19, 2019 15:01
-
-
Save davidfowl/94d1b7d60ad544289b5f60df4c8a6520 to your computer and use it in GitHub Desktop.
Leaking tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
Then I used Visual Studio to see the memory leak.
taking memory snapshots. - so was this to prove something on the compiler side?