Bug 47388

Summary: Memory leak when using FromSynchronizationContext
Product: [Mono] Runtime Reporter: Brandon White <brandonlwhite>
Component: GCAssignee: Vlad Brezae <vlad.brezae>
Status: RESOLVED FIXED    
Severity: normal CC: brandonlwhite, mono-bugs+mono, mono-bugs+runtime, vlad.brezae
Priority: ---    
Version: 4.6.0 (C8)   
Target Milestone: ---   
Hardware: All   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:
Attachments: Minimally reproducing program

Description Brandon White 2016-11-18 18:16:01 UTC
Created attachment 18543 [details]
Minimally reproducing program

When using TaskScheduler.FromSynchronizationContext() frequently, memory is leaked very slowly over time.

This appears to be due to TaskScheduler.s_activeTaskSchedulers retaining entries for TaskSchedulers that are no longer in use.  Whether this is due to ConditionalWeakTable or something else holding on to a reference has yet to be determined.

Attached is a distilled program for reproducing the issue.  Running the program will cause TaskScheduler.FromCurrentSynchronizationContext() to be called roughly every millisecond as part of a Task.Delay.ContinueWith tail-recursive type loop.

If you comment out line 63 and uncomment line 64, you can then observe that the leak does not happen.

We have currently reproduced this on an ARM embedded system as well as an Ubuntu PC, both using Mono 4.2.1.

I will be following up with a test of the latest stable Mono version.
Comment 1 Brandon White 2016-12-01 15:32:05 UTC
I can now confirm that I have reproduced this in 4.6.2.

Mono JIT compiler version 4.6.2 (Stable 4.6.2.7/08fd525 Mon Nov 14 12:30:00 UTC 2016)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  amd64
        Disabled:      none
        Misc:          softdebug
        LLVM:          supported, not enabled.
        GC:            sgen
Comment 2 Vlad Brezae 2017-01-13 01:09:24 UTC
Fixed on mono master by a3b053bacf4436f213391b9776d2ab89b8cf3ff7.