Skip to content

Instantly share code, notes, and snippets.

@MykolaBalakin
Last active November 8, 2019 10:22
Show Gist options
  • Save MykolaBalakin/1f4cfb6097ef0a08c8cb8498da07135b to your computer and use it in GitHub Desktop.
Save MykolaBalakin/1f4cfb6097ef0a08c8cb8498da07135b to your computer and use it in GitHub Desktop.
async + memory leak kind of issue
class Program
{
private const int MegaByte = 1048576;
public static void Main(string[] args)
{
Console.WriteLine("Process ID: " + Process.GetCurrentProcess().Id);
var tasks = new List<Task>();
for (var i = 0; i < 10; i++)
{
tasks.Add(Task.Run(RunAndBlock));
}
Thread.Sleep(TimeSpan.FromSeconds(10));
while (true)
{
Console.WriteLine("Working set: " + Process.GetCurrentProcess().WorkingSet64 / MegaByte + " MB");
Console.ReadLine();
GC.Collect();
}
}
static async Task RunAndBlock()
{
Console.WriteLine($"Started task");
await DoWork();
GC.Collect();
Thread.Sleep(TimeSpan.FromDays(1));
}
static async Task DoWork()
{
var data = AllocateMb(100);
await Task.Yield();
Console.WriteLine($"Allocated {data.Length / 100} MB");
}
static object[] AllocateMb(int mb)
{
var data = new object[mb * 100];
for (var i = 0; i < data.Length; i++)
{
data[i] = Allocate10Kb();
}
return data;
}
static byte[] Allocate10Kb()
{
var random = new Random();
var data = new byte[10240];
random.NextBytes(data);
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment