Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove more LINQ usage from various dotnet/runtime libraries #44964

Merged
merged 16 commits into from
Nov 20, 2020
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -451,35 +450,36 @@ private void Compact(long removalSizeTarget, Func<CacheEntry, long> computeEntry
{
RemoveEntry(entry);
}
}

/// Policy:
/// 1. Least recently used objects.
/// ?. Items with the soonest absolute expiration.
/// ?. Items with the soonest sliding expiration.
/// ?. Larger objects - estimated by object graph size, inaccurate.
private void ExpirePriorityBucket(ref long removedSize, long removalSizeTarget, Func<CacheEntry, long> computeEntrySize, List<CacheEntry> entriesToRemove, List<CacheEntry> priorityEntries)
{
// Do we meet our quota by just removing expired entries?
if (removalSizeTarget <= removedSize)
// Policy:
eerhardt marked this conversation as resolved.
Show resolved Hide resolved
// 1. Least recently used objects.
// ?. Items with the soonest absolute expiration.
// ?. Items with the soonest sliding expiration.
// ?. Larger objects - estimated by object graph size, inaccurate.
static void ExpirePriorityBucket(ref long removedSize, long removalSizeTarget, Func<CacheEntry, long> computeEntrySize, List<CacheEntry> entriesToRemove, List<CacheEntry> priorityEntries)
{
// No-op, we've met quota
return;
}

// Expire enough entries to reach our goal
// TODO: Refine policy
// Do we meet our quota by just removing expired entries?
if (removalSizeTarget <= removedSize)
{
// No-op, we've met quota
return;
}

// LRU
foreach (CacheEntry entry in priorityEntries.OrderBy(entry => entry.LastAccessed))
{
entry.SetExpired(EvictionReason.Capacity);
entriesToRemove.Add(entry);
removedSize += computeEntrySize(entry);
// Expire enough entries to reach our goal
// TODO: Refine policy

if (removalSizeTarget <= removedSize)
// LRU
priorityEntries.Sort((e1, e2) => e1.LastAccessed.CompareTo(e2.LastAccessed));
foreach (CacheEntry entry in priorityEntries)
{
break;
entry.SetExpired(EvictionReason.Capacity);
entriesToRemove.Add(entry);
removedSize += computeEntrySize(entry);

if (removalSizeTarget <= removedSize)
{
break;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;

Expand All @@ -19,7 +18,7 @@ internal sealed class ILEmitResolverBuilder : CallSiteVisitor<ILEmitResolverBuil
private static readonly FieldInfo ConstantsField = typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.Constants));
private static readonly MethodInfo GetTypeFromHandleMethod = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));

private static readonly ConstructorInfo CacheKeyCtor = typeof(ServiceCacheKey).GetConstructors().First();
private static readonly ConstructorInfo CacheKeyCtor = typeof(ServiceCacheKey).GetConstructors()[0];

private class ILEmitResolverBuilderRuntimeContext
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace System.Collections.Generic
public static class CollectionExtensions
{
public static RuntimeAssetGroup GetDefaultGroup(this IEnumerable<RuntimeAssetGroup> self) => GetGroup(self, string.Empty);

public static RuntimeAssetGroup GetRuntimeGroup(this IEnumerable<RuntimeAssetGroup> self, string runtime)
{
if (string.IsNullOrEmpty(runtime))
Expand All @@ -35,9 +36,16 @@ public static IEnumerable<string> GetRuntimeAssets(this IEnumerable<RuntimeAsset

private static IEnumerable<string> GetAssets(IEnumerable<RuntimeAssetGroup> groups, string runtime)
{
return groups
.Where(a => string.Equals(a.Runtime, runtime, StringComparison.Ordinal))
.SelectMany(a => a.AssetPaths);
foreach (RuntimeAssetGroup group in groups)
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
{
if (group.Runtime == runtime)
{
foreach (string path in group.AssetPaths)
{
yield return path;
}
}
}
}

public static IEnumerable<RuntimeFile> GetDefaultRuntimeFileAssets(this IEnumerable<RuntimeAssetGroup> self) => GetRuntimeFiles(self, string.Empty);
Expand All @@ -52,9 +60,16 @@ public static IEnumerable<RuntimeFile> GetRuntimeFileAssets(this IEnumerable<Run

private static IEnumerable<RuntimeFile> GetRuntimeFiles(IEnumerable<RuntimeAssetGroup> groups, string runtime)
{
return groups
.Where(a => string.Equals(a.Runtime, runtime, StringComparison.Ordinal))
.SelectMany(a => a.RuntimeFiles);
foreach (RuntimeAssetGroup group in groups)
{
if (group.Runtime == runtime)
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
{
foreach (RuntimeFile file in group.RuntimeFiles)
{
yield return file;
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Options;

Expand All @@ -29,7 +28,7 @@ public class ConsoleLoggerProvider : ILoggerProvider, ISupportExternalScope
/// </summary>
/// <param name="options">The options to create <see cref="ConsoleLogger"/> instances with.</param>
public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options)
: this(options, Enumerable.Empty<ConsoleFormatter>()) { }
: this(options, Array.Empty<ConsoleFormatter>()) { }

/// <summary>
/// Creates an instance of <see cref="ConsoleLoggerProvider"/>.
Expand Down Expand Up @@ -76,23 +75,26 @@ private static bool DoesConsoleSupportAnsi()

private void SetFormatters(IEnumerable<ConsoleFormatter> formatters = null)
{
_formatters = new ConcurrentDictionary<string, ConsoleFormatter>(StringComparer.OrdinalIgnoreCase);
if (formatters == null || !formatters.Any())
{
var defaultMonitor = new FormatterOptionsMonitor<SimpleConsoleFormatterOptions>(new SimpleConsoleFormatterOptions());
var systemdMonitor = new FormatterOptionsMonitor<ConsoleFormatterOptions>(new ConsoleFormatterOptions());
var jsonMonitor = new FormatterOptionsMonitor<JsonConsoleFormatterOptions>(new JsonConsoleFormatterOptions());
_formatters.GetOrAdd(ConsoleFormatterNames.Simple, formatterName => new SimpleConsoleFormatter(defaultMonitor));
_formatters.GetOrAdd(ConsoleFormatterNames.Systemd, formatterName => new SystemdConsoleFormatter(systemdMonitor));
_formatters.GetOrAdd(ConsoleFormatterNames.Json, formatterName => new JsonConsoleFormatter(jsonMonitor));
}
else
var cd = new ConcurrentDictionary<string, ConsoleFormatter>(StringComparer.OrdinalIgnoreCase);

bool added = false;
if (formatters != null)
{
foreach (ConsoleFormatter formatter in formatters)
{
_formatters.GetOrAdd(formatter.Name, formatterName => formatter);
cd.TryAdd(formatter.Name, formatter);
added = true;
}
}

if (!added)
{
cd.TryAdd(ConsoleFormatterNames.Simple, new SimpleConsoleFormatter(new FormatterOptionsMonitor<SimpleConsoleFormatterOptions>(new SimpleConsoleFormatterOptions())));
cd.TryAdd(ConsoleFormatterNames.Systemd, new SystemdConsoleFormatter(new FormatterOptionsMonitor<ConsoleFormatterOptions>(new ConsoleFormatterOptions())));
cd.TryAdd(ConsoleFormatterNames.Json, new JsonConsoleFormatter(new FormatterOptionsMonitor<JsonConsoleFormatterOptions>(new JsonConsoleFormatterOptions())));
}

_formatters = cd;
}

// warning: ReloadLoggerOptions can be called before the ctor completed,... before registering all of the state used in this method need to be initialized
Expand Down Expand Up @@ -135,7 +137,7 @@ public ILogger CreateLogger(string name)
{
UpdateFormatterOptions(logFormatter, _options.CurrentValue);
}
#pragma warning disable CS0618
#pragma warning restore CS0618
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
}

return _loggers.GetOrAdd(name, loggerName => new ConsoleLogger(name, _messageQueue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

Expand All @@ -28,7 +27,7 @@ public class LoggerFactory : ILoggerFactory
/// <summary>
/// Creates a new <see cref="LoggerFactory"/> instance.
/// </summary>
public LoggerFactory() : this(Enumerable.Empty<ILoggerProvider>())
public LoggerFactory() : this(Array.Empty<ILoggerProvider>())
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
{
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Microsoft.Extensions.Options
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

Expand Down Expand Up @@ -146,28 +144,29 @@ public static IServiceCollection PostConfigureAll<TOptions>(this IServiceCollect
where TConfigureOptions : class
=> services.ConfigureOptions(typeof(TConfigureOptions));

private static bool IsAction(Type type)
=> (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Action<>));

private static IEnumerable<Type> FindConfigurationServices(Type type)
{
IEnumerable<Type> serviceTypes = type
.GetInterfaces()
.Where(t => t.IsGenericType)
.Where(t =>
t.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) ||
t.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) ||
t.GetGenericTypeDefinition() == typeof(IValidateOptions<>));
if (!serviceTypes.Any())
foreach (Type t in type.GetInterfaces())
{
throw new InvalidOperationException(
IsAction(type)
? SR.Error_NoConfigurationServicesAndAction
: SR.Error_NoConfigurationServices);
if (t.IsGenericType)
{
Type gtd = t.GetGenericTypeDefinition();
if (gtd == typeof(IConfigureOptions<>) ||
gtd == typeof(IPostConfigureOptions<>) ||
gtd == typeof(IValidateOptions<>))
{
yield return t;
}
}
}
return serviceTypes;
}

private static void ThrowNoConfigServices(Type type) =>
throw new InvalidOperationException(
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Action<>) ?
SR.Error_NoConfigurationServicesAndAction :
SR.Error_NoConfigurationServices);

/// <summary>
/// Registers a type that will have all of its <see cref="IConfigureOptions{TOptions}"/>,
/// <see cref="IPostConfigureOptions{TOptions}"/>, and <see cref="IValidateOptions{TOptions}"/>
Expand All @@ -181,11 +180,19 @@ public static IServiceCollection ConfigureOptions(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type configureType)
{
services.AddOptions();
IEnumerable<Type> serviceTypes = FindConfigurationServices(configureType);
foreach (Type serviceType in serviceTypes)

bool added = false;
foreach (Type serviceType in FindConfigurationServices(configureType))
{
services.AddTransient(serviceType, configureType);
added = true;
}

if (!added)
{
ThrowNoConfigServices(configureType);
}

return services;
}

Expand All @@ -200,11 +207,20 @@ public static IServiceCollection ConfigureOptions(
public static IServiceCollection ConfigureOptions(this IServiceCollection services, object configureInstance)
{
services.AddOptions();
IEnumerable<Type> serviceTypes = FindConfigurationServices(configureInstance.GetType());
foreach (Type serviceType in serviceTypes)
Type configureType = configureInstance.GetType();

bool added = false;
foreach (Type serviceType in FindConfigurationServices(configureType))
{
services.AddSingleton(serviceType, configureInstance);
added = true;
}

if (!added)
{
ThrowNoConfigServices(configureType);
}

return services;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,6 @@
<Reference Include="System.Diagnostics.FileVersionInfo" />
<Reference Include="System.IO.FileSystem" />
<Reference Include="System.IO.FileSystem.DriveInfo" />
<Reference Include="System.Linq" />
<Reference Include="System.Memory" />
<Reference Include="System.Net.Sockets" />
<Reference Include="System.Runtime" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,24 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace System.Diagnostics
{
internal static partial class ProcessManager
{
/// <summary>Gets the IDs of all processes on the current machine.</summary>
public static int[] GetProcessIds()
{
return EnumerateProcessIds().ToArray();
}
public static int[] GetProcessIds() => new List<int>(EnumerateProcessIds()).ToArray();
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>Gets process infos for each process on the specified machine.</summary>
/// <param name="machineName">The target machine.</param>
/// <returns>An array of process infos, one per found process.</returns>
public static ProcessInfo[] GetProcessInfos(string machineName)
{
ThrowIfRemoteMachine(machineName);
int[] procIds = GetProcessIds(machineName);

// Iterate through all process IDs to load information about each process
var processes = new List<ProcessInfo>(procIds.Length);
foreach (int pid in procIds)
var processes = new List<ProcessInfo>();
foreach (int pid in EnumerateProcessIds())
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
{
ProcessInfo? pi = CreateProcessInfo(pid);
if (pi != null)
Expand Down
Loading