Skip to content

Commit 820f1e2

Browse files
authored
Removed WeakReference<IHosts> already cleaned up by GC (#4995)
* Removing unused IHosts * Removed unused hosts in both Register methods
1 parent 77e7f98 commit 820f1e2

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/Microsoft.ML.Core/Environment/HostEnvironmentBase.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,12 +127,18 @@ public HostBase(HostEnvironmentBase<TEnv> source, string shortName, string paren
127127
Depth = source.Depth + 1;
128128
}
129129

130+
/// <summary>
131+
/// This method registers and returns the host for the calling component. The generated host is also
132+
/// added to <see cref="_children"/> and encapsulated by <see cref="WeakReference"/>. It becomes
133+
/// necessary to remove these hosts when they are reclaimed by the Garbage Collector.
134+
/// </summary>
130135
public new IHost Register(string name, int? seed = null, bool? verbose = null)
131136
{
132137
Contracts.CheckNonEmpty(name, nameof(name));
133138
IHost host;
134139
lock (_cancelLock)
135140
{
141+
_children.RemoveAll(r => r.TryGetTarget(out IHost _) == false);
136142
Random rand = (seed.HasValue) ? RandomUtils.Create(seed.Value) : RandomUtils.Create(_rand);
137143
host = RegisterCore(this, name, Master?.FullName, rand, verbose ?? Verbose);
138144
if (!IsCanceled)
@@ -385,12 +391,18 @@ protected HostEnvironmentBase(HostEnvironmentBase<TEnv> source, Random rand, boo
385391
_children = new List<WeakReference<IHost>>();
386392
}
387393

394+
/// <summary>
395+
/// This method registers and returns the host for the calling component. The generated host is also
396+
/// added to <see cref="_children"/> and encapsulated by <see cref="WeakReference"/>. It becomes
397+
/// necessary to remove these hosts when they are reclaimed by the Garbage Collector.
398+
/// </summary>
388399
public IHost Register(string name, int? seed = null, bool? verbose = null)
389400
{
390401
Contracts.CheckNonEmpty(name, nameof(name));
391402
IHost host;
392403
lock (_cancelLock)
393404
{
405+
_children.RemoveAll(r => r.TryGetTarget(out IHost _) == false);
394406
Random rand = (seed.HasValue) ? RandomUtils.Create(seed.Value) : RandomUtils.Create(_rand);
395407
host = RegisterCore(this, name, Master?.FullName, rand, verbose ?? Verbose);
396408
_children.Add(new WeakReference<IHost>(host));

0 commit comments

Comments
 (0)