Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Missed new file in last commit.
  • Loading branch information
StephenMolloy committed Oct 28, 2021
commit 6ab0bcd5678fdd20974fb7b24b87894441e01617
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Xml.Serialization
{
using System;
using System.Collections;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usings should be outside of namespace

using System.Runtime.CompilerServices;
using System.Runtime.Loader;

internal class ContextAwareTables<T> where T : class?
{
private Hashtable _defaultTable;
private ConditionalWeakTable<Type, T> _collectibleTable;

public ContextAwareTables()
{
_defaultTable = new Hashtable();
_collectibleTable = new ConditionalWeakTable<Type, T>();
}

internal T GetOrCreateValue(Type t, Func<T> f)
{
T? ret;
AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(t.Assembly);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How expensive is ALC.GetLoadContext? If it's non-trivial, it might be worth always checking the default table first and only using GetLoadContext to see which table is should go in if not found in the default. If it's cheap, then this is fine.

// Null and non-collectible load contexts use the default table
if (alc == null || !alc.IsCollectible)
{
if ((ret = (T?)_defaultTable[t]) == null)
{
lock (_defaultTable)
{
if ((ret = (T?)_defaultTable[t]) == null)
{
ret = f();
_defaultTable[t] = ret;
}
}
}
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded
else
{
if (!_collectibleTable.TryGetValue(t, out ret))
{
lock (_collectibleTable)
{
if (!_collectibleTable.TryGetValue(t, out ret))
{
ret = f();
_collectibleTable.AddOrUpdate(t, ret);
}
}
}
}

return ret;
}
}
}