diff --git a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBGatewayListProviderHelper.cs b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBGatewayListProviderHelper.cs index 4db18800b6..96e59cb1d6 100644 --- a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBGatewayListProviderHelper.cs +++ b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBGatewayListProviderHelper.cs @@ -22,7 +22,7 @@ internal static void ParseDataConnectionString(string dataConnectionString, Dyna { var parameters = dataConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - var serviceConfig = parameters.Where(p => p.Contains(ServicePropertyName)).FirstOrDefault(); + var serviceConfig = Array.Find(parameters, p => p.Contains(ServicePropertyName)); if (!string.IsNullOrWhiteSpace(serviceConfig)) { var value = serviceConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -30,7 +30,7 @@ internal static void ParseDataConnectionString(string dataConnectionString, Dyna options.Service = value[1]; } - var secretKeyConfig = parameters.Where(p => p.Contains(SecretKeyPropertyName)).FirstOrDefault(); + var secretKeyConfig = Array.Find(parameters, p => p.Contains(SecretKeyPropertyName)); if (!string.IsNullOrWhiteSpace(secretKeyConfig)) { var value = secretKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -38,7 +38,7 @@ internal static void ParseDataConnectionString(string dataConnectionString, Dyna options.SecretKey = value[1]; } - var accessKeyConfig = parameters.Where(p => p.Contains(AccessKeyPropertyName)).FirstOrDefault(); + var accessKeyConfig = Array.Find(parameters, p => p.Contains(AccessKeyPropertyName)); if (!string.IsNullOrWhiteSpace(accessKeyConfig)) { var value = accessKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -46,7 +46,7 @@ internal static void ParseDataConnectionString(string dataConnectionString, Dyna options.AccessKey = value[1]; } - var readCapacityUnitsConfig = parameters.Where(p => p.Contains(ReadCapacityUnitsPropertyName)).FirstOrDefault(); + var readCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(ReadCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(readCapacityUnitsConfig)) { var value = readCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -54,7 +54,7 @@ internal static void ParseDataConnectionString(string dataConnectionString, Dyna options.ReadCapacityUnits = int.Parse(value[1]); } - var writeCapacityUnitsConfig = parameters.Where(p => p.Contains(WriteCapacityUnitsPropertyName)).FirstOrDefault(); + var writeCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(WriteCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(writeCapacityUnitsConfig)) { var value = writeCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); diff --git a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipHelper.cs b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipHelper.cs index 96f8d5bffc..52efee8885 100644 --- a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipHelper.cs +++ b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipHelper.cs @@ -23,7 +23,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo { var parameters = dataConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - var serviceConfig = parameters.Where(p => p.Contains(ServicePropertyName)).FirstOrDefault(); + var serviceConfig = Array.Find(parameters, p => p.Contains(ServicePropertyName)); if (!string.IsNullOrWhiteSpace(serviceConfig)) { var value = serviceConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -31,7 +31,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo options.Service = value[1]; } - var tableNameConfig = parameters.Where(p => p.Contains(TableNamePropertyName)).FirstOrDefault(); + var tableNameConfig = Array.Find(parameters, p => p.Contains(TableNamePropertyName)); if (!string.IsNullOrWhiteSpace(tableNameConfig)) { var value = tableNameConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -39,7 +39,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo options.TableName = value[1]; } - var secretKeyConfig = parameters.Where(p => p.Contains(SecretKeyPropertyName)).FirstOrDefault(); + var secretKeyConfig = Array.Find(parameters, p => p.Contains(SecretKeyPropertyName)); if (!string.IsNullOrWhiteSpace(secretKeyConfig)) { var value = secretKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -47,7 +47,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo options.SecretKey = value[1]; } - var accessKeyConfig = parameters.Where(p => p.Contains(AccessKeyPropertyName)).FirstOrDefault(); + var accessKeyConfig = Array.Find(parameters, p => p.Contains(AccessKeyPropertyName)); if (!string.IsNullOrWhiteSpace(accessKeyConfig)) { var value = accessKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -55,7 +55,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo options.AccessKey = value[1]; } - var readCapacityUnitsConfig = parameters.Where(p => p.Contains(ReadCapacityUnitsPropertyName)).FirstOrDefault(); + var readCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(ReadCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(readCapacityUnitsConfig)) { var value = readCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -63,7 +63,7 @@ public static void ParseDataConnectionString(string dataConnectionString, Dynamo options.ReadCapacityUnits = int.Parse(value[1]); } - var writeCapacityUnitsConfig = parameters.Where(p => p.Contains(WriteCapacityUnitsPropertyName)).FirstOrDefault(); + var writeCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(WriteCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(writeCapacityUnitsConfig)) { var value = writeCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); diff --git a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipTable.cs b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipTable.cs index c64cf624f3..a2ea643640 100644 --- a/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipTable.cs +++ b/src/AWS/Orleans.Clustering.DynamoDB/Membership/DynamoDBMembershipTable.cs @@ -223,7 +223,7 @@ public async Task ReadAll() var keys = new Dictionary { { $":{SiloInstanceRecord.DEPLOYMENT_ID_PROPERTY_NAME}", new AttributeValue(this.clusterId) } }; var records = await this.storage.QueryAllAsync(this.options.TableName, keys, $"{SiloInstanceRecord.DEPLOYMENT_ID_PROPERTY_NAME} = :{SiloInstanceRecord.DEPLOYMENT_ID_PROPERTY_NAME}", item => new SiloInstanceRecord(item)); - if (records.Any(record => record.MembershipVersion > versionRow.MembershipVersion)) + if (records.Exists(record => record.MembershipVersion > versionRow.MembershipVersion)) { this.logger.LogWarning((int)ErrorCode.MembershipBase, "Found an inconsistency while reading all silo entries"); //not expecting this to hit often, but if it does, should put in a limit diff --git a/src/AWS/Orleans.Reminders.DynamoDB/Reminders/DynamoDbReminderStorageOptionsExtensions.cs b/src/AWS/Orleans.Reminders.DynamoDB/Reminders/DynamoDbReminderStorageOptionsExtensions.cs index 9a23084e43..3f890f607b 100644 --- a/src/AWS/Orleans.Reminders.DynamoDB/Reminders/DynamoDbReminderStorageOptionsExtensions.cs +++ b/src/AWS/Orleans.Reminders.DynamoDB/Reminders/DynamoDbReminderStorageOptionsExtensions.cs @@ -24,7 +24,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt { var parameters = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - var serviceConfig = parameters.Where(p => p.Contains(ServicePropertyName)).FirstOrDefault(); + var serviceConfig = Array.Find(parameters, p => p.Contains(ServicePropertyName)); if (!string.IsNullOrWhiteSpace(serviceConfig)) { var value = serviceConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -32,7 +32,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.Service = value[1]; } - var secretKeyConfig = parameters.Where(p => p.Contains(SecretKeyPropertyName)).FirstOrDefault(); + var secretKeyConfig = Array.Find(parameters, p => p.Contains(SecretKeyPropertyName)); if (!string.IsNullOrWhiteSpace(secretKeyConfig)) { var value = secretKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -40,7 +40,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.SecretKey = value[1]; } - var accessKeyConfig = parameters.Where(p => p.Contains(AccessKeyPropertyName)).FirstOrDefault(); + var accessKeyConfig = Array.Find(parameters, p => p.Contains(AccessKeyPropertyName)); if (!string.IsNullOrWhiteSpace(accessKeyConfig)) { var value = accessKeyConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -48,7 +48,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.AccessKey = value[1]; } - var readCapacityUnitsConfig = parameters.Where(p => p.Contains(ReadCapacityUnitsPropertyName)).FirstOrDefault(); + var readCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(ReadCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(readCapacityUnitsConfig)) { var value = readCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -56,7 +56,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.ReadCapacityUnits = int.Parse(value[1]); } - var writeCapacityUnitsConfig = parameters.Where(p => p.Contains(WriteCapacityUnitsPropertyName)).FirstOrDefault(); + var writeCapacityUnitsConfig = Array.Find(parameters, p => p.Contains(WriteCapacityUnitsPropertyName)); if (!string.IsNullOrWhiteSpace(writeCapacityUnitsConfig)) { var value = writeCapacityUnitsConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -64,7 +64,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.WriteCapacityUnits = int.Parse(value[1]); } - var useProvisionedThroughputConfig = parameters.Where(p => p.Contains(UseProvisionedThroughputPropertyName)).FirstOrDefault(); + var useProvisionedThroughputConfig = Array.Find(parameters, p => p.Contains(UseProvisionedThroughputPropertyName)); if (!string.IsNullOrWhiteSpace(useProvisionedThroughputConfig)) { var value = useProvisionedThroughputConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -72,7 +72,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.UseProvisionedThroughput = bool.Parse(value[1]); } - var createIfNotExistsPropertyNameConfig = parameters.Where(p => p.Contains(CreateIfNotExistsPropertyName)).FirstOrDefault(); + var createIfNotExistsPropertyNameConfig = Array.Find(parameters, p => p.Contains(CreateIfNotExistsPropertyName)); if (!string.IsNullOrWhiteSpace(createIfNotExistsPropertyNameConfig)) { var value = createIfNotExistsPropertyNameConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); @@ -80,7 +80,7 @@ public static void ParseConnectionString(this DynamoDBReminderStorageOptions opt options.CreateIfNotExists = bool.Parse(value[1]); } - var updateIfExistsPropertyNameConfig = parameters.Where(p => p.Contains(UpdateIfExistsPropertyName)).FirstOrDefault(); + var updateIfExistsPropertyNameConfig = Array.Find(parameters, p => p.Contains(UpdateIfExistsPropertyName)); if (!string.IsNullOrWhiteSpace(updateIfExistsPropertyNameConfig)) { var value = updateIfExistsPropertyNameConfig.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); diff --git a/src/AWS/Orleans.Streaming.SQS/Storage/SQSStorage.cs b/src/AWS/Orleans.Streaming.SQS/Storage/SQSStorage.cs index e4e73d1265..58f9dff811 100644 --- a/src/AWS/Orleans.Streaming.SQS/Storage/SQSStorage.cs +++ b/src/AWS/Orleans.Streaming.SQS/Storage/SQSStorage.cs @@ -1,14 +1,14 @@ -using Amazon.Runtime; -using Amazon.SQS; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Amazon.Runtime; +using Amazon.SQS; using Amazon.SQS.Model; using Microsoft.Extensions.Logging; +using Orleans; using Orleans.Streaming.SQS; using SQSMessage = Amazon.SQS.Model.Message; -using Orleans; namespace OrleansAWSUtils.Storage { @@ -55,7 +55,7 @@ private void ParseDataConnectionString(string dataConnectionString) { var parameters = dataConnectionString.Split(';', StringSplitOptions.RemoveEmptyEntries); - var serviceConfig = parameters.FirstOrDefault(p => p.Contains(ServicePropertyName)); + var serviceConfig = Array.Find(parameters, p => p.Contains(ServicePropertyName)); if (!string.IsNullOrWhiteSpace(serviceConfig)) { var value = serviceConfig.Split('=', StringSplitOptions.RemoveEmptyEntries); @@ -63,7 +63,7 @@ private void ParseDataConnectionString(string dataConnectionString) service = value[1]; } - var secretKeyConfig = parameters.FirstOrDefault(p => p.Contains(SecretKeyPropertyName)); + var secretKeyConfig = Array.Find(parameters, p => p.Contains(SecretKeyPropertyName)); if (!string.IsNullOrWhiteSpace(secretKeyConfig)) { var value = secretKeyConfig.Split('=', StringSplitOptions.RemoveEmptyEntries); @@ -71,7 +71,7 @@ private void ParseDataConnectionString(string dataConnectionString) secretKey = value[1]; } - var accessKeyConfig = parameters.FirstOrDefault(p => p.Contains(AccessKeyPropertyName)); + var accessKeyConfig = Array.Find(parameters, p => p.Contains(AccessKeyPropertyName)); if (!string.IsNullOrWhiteSpace(accessKeyConfig)) { var value = accessKeyConfig.Split('=', StringSplitOptions.RemoveEmptyEntries); diff --git a/src/AWS/Shared/Storage/DynamoDBStorage.cs b/src/AWS/Shared/Storage/DynamoDBStorage.cs index 6f45ab120d..445077edd4 100755 --- a/src/AWS/Shared/Storage/DynamoDBStorage.cs +++ b/src/AWS/Shared/Storage/DynamoDBStorage.cs @@ -429,7 +429,7 @@ private async Task TableIndexWaitOnStatusAsync(string tableNam } ret = await GetTableDescription(tableName); - index = ret.GlobalSecondaryIndexes.FirstOrDefault(index => index.IndexName == indexName); + index = ret.GlobalSecondaryIndexes.Find(index => index.IndexName == indexName); } while (index.IndexStatus == whileStatus); if (desiredStatus != null && index.IndexStatus != desiredStatus) diff --git a/src/Azure/Orleans.Hosting.AzureCloudServices/Hosting/ServiceRuntimeWrapper.cs b/src/Azure/Orleans.Hosting.AzureCloudServices/Hosting/ServiceRuntimeWrapper.cs index bf09deebea..75de191840 100644 --- a/src/Azure/Orleans.Hosting.AzureCloudServices/Hosting/ServiceRuntimeWrapper.cs +++ b/src/Azure/Orleans.Hosting.AzureCloudServices/Hosting/ServiceRuntimeWrapper.cs @@ -181,7 +181,7 @@ public void UnsubscribeFromStoppingNotification(object handlerObject, EventHandl private void Initialize() { - assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault( + assembly = Array.Find(AppDomain.CurrentDomain.GetAssemblies(), a => a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime", StringComparison.Ordinal)); // If we are runing within a worker role Microsoft.WindowsAzure.ServiceRuntime should already be loaded diff --git a/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/CachePressureMonitors/AggregatedCachePressureMonitor.cs b/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/CachePressureMonitors/AggregatedCachePressureMonitor.cs index 67e01f6cef..a110ee955a 100644 --- a/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/CachePressureMonitors/AggregatedCachePressureMonitor.cs +++ b/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/CachePressureMonitors/AggregatedCachePressureMonitor.cs @@ -58,7 +58,7 @@ public void AddCachePressureMonitor(ICachePressureMonitor monitor) /// public bool IsUnderPressure(DateTime utcNow) { - bool underPressure = this.Any(monitor => monitor.IsUnderPressure(utcNow)); + bool underPressure = this.Exists(monitor => monitor.IsUnderPressure(utcNow)); if (this.isUnderPressure != underPressure) { this.isUnderPressure = underPressure; diff --git a/src/Orleans.Analyzers/AliasClashAttributeAnalyzer.cs b/src/Orleans.Analyzers/AliasClashAttributeAnalyzer.cs index 622df81140..de0ea2c85b 100644 --- a/src/Orleans.Analyzers/AliasClashAttributeAnalyzer.cs +++ b/src/Orleans.Analyzers/AliasClashAttributeAnalyzer.cs @@ -84,7 +84,7 @@ private void CheckSyntaxNode(SyntaxNodeAnalysisContext context) { ++suffix; newAlias = $"{prefix}{suffix}"; - } while (bags.Any(x => x.Value.Equals(newAlias, StringComparison.Ordinal))); + } while (bags.Exists(x => x.Value.Equals(newAlias, StringComparison.Ordinal))); var builder = ImmutableDictionary.CreateBuilder(); diff --git a/src/Orleans.Analyzers/IdClashAttributeCodeFix.cs b/src/Orleans.Analyzers/IdClashAttributeCodeFix.cs index 021e27b9d8..756ceb70a3 100644 --- a/src/Orleans.Analyzers/IdClashAttributeCodeFix.cs +++ b/src/Orleans.Analyzers/IdClashAttributeCodeFix.cs @@ -38,7 +38,6 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) .OfType() .Where(a => a.IsAttribute(Constants.IdAttributeName)) .Select(a => int.Parse(a.ArgumentList.Arguments.Single().ToString())) - .ToList() .Max() + 1; var newAttribute = attribute.ReplaceNode( diff --git a/src/Orleans.Clustering.Consul/ConsulBasedMembershipTable.cs b/src/Orleans.Clustering.Consul/ConsulBasedMembershipTable.cs index 359c7898a0..37c40760fc 100644 --- a/src/Orleans.Clustering.Consul/ConsulBasedMembershipTable.cs +++ b/src/Orleans.Clustering.Consul/ConsulBasedMembershipTable.cs @@ -1,14 +1,14 @@ using System; +using System.Collections.Generic; +using System.Globalization; using System.Linq; +using System.Text; using System.Threading.Tasks; using Consul; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Runtime.Host; -using System.Collections.Generic; -using System.Text; -using System.Globalization; namespace Orleans.Runtime.Membership { @@ -80,7 +80,7 @@ public static async Task ReadAll(IConsulClient consulClient && !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.VersionSuffix, StringComparison.OrdinalIgnoreCase)) .Select(siloKV => { - var iAmAliveKV = deploymentKVAddresses.Response.Where(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); + var iAmAliveKV = deploymentKVAddresses.Response.SingleOrDefault(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)); return ConsulSiloRegistrationAssembler.FromKVPairs(clusterId, siloKV, iAmAliveKV); }).ToArray(); @@ -223,7 +223,7 @@ public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate) && !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.VersionSuffix, StringComparison.OrdinalIgnoreCase)) .Select(siloKV => { - var iAmAliveKV = allKVs.Response.Where(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); + var iAmAliveKV = allKVs.Response.SingleOrDefault(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)); return new { RegistrationKey = siloKV.Key, diff --git a/src/Orleans.CodeGenerator/FieldIdAssignmentHelper.cs b/src/Orleans.CodeGenerator/FieldIdAssignmentHelper.cs index 71c30724b3..caddfd7a32 100644 --- a/src/Orleans.CodeGenerator/FieldIdAssignmentHelper.cs +++ b/src/Orleans.CodeGenerator/FieldIdAssignmentHelper.cs @@ -37,7 +37,7 @@ public FieldIdAssignmentHelper(INamedTypeSymbol typeSymbol, ImmutableArray _symbols.TryGetValue(symbol, out key); - private bool HasMemberWithIdAnnotation() => _memberSymbols.Any(member => member.HasAnyAttribute(_libraryTypes.IdAttributeTypes)); + private bool HasMemberWithIdAnnotation() => Array.Exists(_memberSymbols, member => member.HasAnyAttribute(_libraryTypes.IdAttributeTypes)); private IEnumerable GetMembers(INamedTypeSymbol symbol) { diff --git a/src/Orleans.Core.Abstractions/Utils/Utils.cs b/src/Orleans.Core.Abstractions/Utils/Utils.cs index 13b71e0c10..638520bc47 100644 --- a/src/Orleans.Core.Abstractions/Utils/Utils.cs +++ b/src/Orleans.Core.Abstractions/Utils/Utils.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; +using System.Threading.Tasks; using Microsoft.Extensions.Logging; #nullable enable @@ -179,6 +180,15 @@ public static void SafeExecute(Action action, ILogger? logger = null, string? ca } } + public static async Task SafeExecuteAsync(Task task) + { + try + { + await task; + } + catch { } + } + internal static void LogIgnoredException(ILogger logger, Exception exc, string? caller) { try diff --git a/src/Orleans.Core/Async/TaskExtensions.cs b/src/Orleans.Core/Async/TaskExtensions.cs index 21c7fe9801..ff6721f2a3 100644 --- a/src/Orleans.Core/Async/TaskExtensions.cs +++ b/src/Orleans.Core/Async/TaskExtensions.cs @@ -76,7 +76,7 @@ public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, return; } - var timeoutCancellationTokenSource = new CancellationTokenSource(); + using var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result @@ -110,7 +110,7 @@ public static async Task WithTimeout(this Task taskToComplete, TimeSpan return await taskToComplete; } - var timeoutCancellationTokenSource = new CancellationTokenSource(); + using var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result diff --git a/src/Orleans.Core/Configuration/ConfigUtilities.cs b/src/Orleans.Core/Configuration/ConfigUtilities.cs index 5d6d91e2d6..da4f76ace8 100644 --- a/src/Orleans.Core/Configuration/ConfigUtilities.cs +++ b/src/Orleans.Core/Configuration/ConfigUtilities.cs @@ -225,7 +225,7 @@ public static string RedactConnectionStringInfo(string connectionString) var mark = "<--SNIP-->"; if (string.IsNullOrEmpty(connectionString)) return "null"; //if connection string format doesn't contain any secretKey, then return just <--SNIP--> - if (!secretKeys.Any(key => connectionString.Contains(key))) return mark; + if (!Array.Exists(secretKeys, key => connectionString.Contains(key))) return mark; string connectionInfo = connectionString; diff --git a/src/Orleans.Hosting.Kubernetes/KubernetesClusterAgent.cs b/src/Orleans.Hosting.Kubernetes/KubernetesClusterAgent.cs index 98ba7e6bd8..ad851685c8 100644 --- a/src/Orleans.Hosting.Kubernetes/KubernetesClusterAgent.cs +++ b/src/Orleans.Hosting.Kubernetes/KubernetesClusterAgent.cs @@ -223,7 +223,7 @@ private async Task MonitorOrleansClustering() .Take(_options.CurrentValue.MaxAgents) .ToList(); - if (!_enableMonitoring && chosenSilos.Any(s => s.SiloAddress.Equals(_localSiloDetails.SiloAddress))) + if (!_enableMonitoring && chosenSilos.Exists(s => s.SiloAddress.Equals(_localSiloDetails.SiloAddress))) { _enableMonitoring = true; _pauseMonitoringSemaphore.Release(1); diff --git a/src/Orleans.Runtime/Catalog/ActivationCollector.cs b/src/Orleans.Runtime/Catalog/ActivationCollector.cs index 1fa6a1933e..a0da522af4 100644 --- a/src/Orleans.Runtime/Catalog/ActivationCollector.cs +++ b/src/Orleans.Runtime/Catalog/ActivationCollector.cs @@ -505,7 +505,7 @@ private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = de private async Task DeactivateActivationsFromCollector(List list) { - var cts = new CancellationTokenSource(_options.Value.DeactivationTimeout); + using var cts = new CancellationTokenSource(_options.Value.DeactivationTimeout); var mtcs = new MultiTaskCompletionSource(list.Count); logger.LogInformation((int)ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {Count} to promptly Destroy.", list.Count); diff --git a/src/Orleans.Runtime/Catalog/Catalog.cs b/src/Orleans.Runtime/Catalog/Catalog.cs index 6558349335..282a3ce374 100644 --- a/src/Orleans.Runtime/Catalog/Catalog.cs +++ b/src/Orleans.Runtime/Catalog/Catalog.cs @@ -354,7 +354,7 @@ internal async Task DeactivateActivations(DeactivationReason reason, List activation.DeactivateAsync(reason, timeoutTokenSource.Token))); } @@ -401,9 +401,9 @@ public SiloStatus LocalSiloStatus } } - public Task DeleteActivations(List addresses, DeactivationReasonCode reasonCode, string reasonText) + public async Task DeleteActivations(List addresses, DeactivationReasonCode reasonCode, string reasonText) { - var timeoutTokenSource = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout); + using var timeoutTokenSource = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout); var tasks = new List(addresses.Count); var deactivationReason = new DeactivationReason(reasonCode, reasonText); foreach (var activationAddress in addresses) @@ -414,7 +414,7 @@ public Task DeleteActivations(List addresses, DeactivationReasonCo } } - return Task.WhenAll(tasks); + await Task.WhenAll(tasks); } // TODO move this logic in the LocalGrainDirectory diff --git a/src/Orleans.Runtime/MembershipService/MembershipTableManager.cs b/src/Orleans.Runtime/MembershipService/MembershipTableManager.cs index 8d3f55986f..2f8a48e9b7 100644 --- a/src/Orleans.Runtime/MembershipService/MembershipTableManager.cs +++ b/src/Orleans.Runtime/MembershipService/MembershipTableManager.cs @@ -347,7 +347,7 @@ async Task UpdateMyStatusTask(int counter) var gossipTask = this.GossipToOthers(this.myAddress, status); gossipTask.Ignore(); - var cancellation = new CancellationTokenSource(); + using var cancellation = new CancellationTokenSource(); var timeoutTask = Task.Delay(GossipTimeout, cancellation.Token); var task = await Task.WhenAny(gossipTask, timeoutTask); if (ReferenceEquals(task, timeoutTask)) diff --git a/src/Orleans.Runtime/MembershipService/SiloHealthMonitor.cs b/src/Orleans.Runtime/MembershipService/SiloHealthMonitor.cs index c8491fa5f9..5aadb68c96 100644 --- a/src/Orleans.Runtime/MembershipService/SiloHealthMonitor.cs +++ b/src/Orleans.Runtime/MembershipService/SiloHealthMonitor.cs @@ -175,7 +175,7 @@ private async Task Run() var isDirectProbe = !_clusterMembershipOptions.CurrentValue.EnableIndirectProbes || _failedProbes < _clusterMembershipOptions.CurrentValue.NumMissedProbesLimit - 1 || otherNodes.Length == 0; var timeout = GetTimeout(isDirectProbe); - var cancellation = new CancellationTokenSource(timeout); + using var cancellation = new CancellationTokenSource(timeout); if (isDirectProbe) { diff --git a/src/Orleans.Runtime/Services/GrainServicesSiloBuilderExtensions.cs b/src/Orleans.Runtime/Services/GrainServicesSiloBuilderExtensions.cs index 14b2b880b4..97838ebee6 100644 --- a/src/Orleans.Runtime/Services/GrainServicesSiloBuilderExtensions.cs +++ b/src/Orleans.Runtime/Services/GrainServicesSiloBuilderExtensions.cs @@ -1,9 +1,9 @@ +using System; +using System.Linq; using Microsoft.Extensions.DependencyInjection; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Services; -using System; -using System.Linq; namespace Orleans.Hosting { @@ -26,7 +26,7 @@ public static ISiloBuilder AddGrainService(this ISiloBuilder builder) private static IGrainService GrainServiceFactory(Type serviceType, IServiceProvider services) { - var grainServiceInterfaceType = serviceType.GetInterfaces().FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IGrainService))); + var grainServiceInterfaceType = Array.Find(serviceType.GetInterfaces(), x => x.GetInterfaces().Contains(typeof(IGrainService))); if (grainServiceInterfaceType is null) { throw new InvalidOperationException(string.Format($"Cannot find an interface on {serviceType.FullName} which implements IGrainService")); diff --git a/src/Orleans.Runtime/Silo/Silo.cs b/src/Orleans.Runtime/Silo/Silo.cs index 1c686b51d0..7268a37e06 100644 --- a/src/Orleans.Runtime/Silo/Silo.cs +++ b/src/Orleans.Runtime/Silo/Silo.cs @@ -161,7 +161,7 @@ public Silo(ILocalSiloDetails siloDetails, IServiceProvider services) this.siloLifecycle = this.Services.GetRequiredService(); // register all lifecycle participants IEnumerable> lifecycleParticipants = this.Services.GetServices>(); - foreach(ILifecycleParticipant participant in lifecycleParticipants) + foreach (ILifecycleParticipant participant in lifecycleParticipants) { participant?.Participate(this.siloLifecycle); } @@ -357,7 +357,7 @@ private async Task StartGrainService(IGrainService service) var grainService = (GrainService)service; await grainService.QueueTask(grainService.Start).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}"); - logger.LogInformation("Grain Service {GrainServiceType} started successfully.",service.GetType().FullName); + logger.LogInformation("Grain Service {GrainServiceType} started successfully.", service.GetType().FullName); } /// @@ -423,10 +423,10 @@ public async Task StopAsync(CancellationToken cancellationToken) { logger.LogDebug((int)ErrorCode.SiloStopInProgress, "Silo shutdown in progress. Waiting for shutdown to be completed."); } - var pause = TimeSpan.FromSeconds(1); + var pause = TimeSpan.FromSeconds(1); while (!this.SystemStatus.Equals(SystemStatus.Terminated)) - { + { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug((int)ErrorCode.WaitingForSiloStop, "Silo shutdown still in progress..."); @@ -494,7 +494,7 @@ private Task OnRuntimeServicesStop(CancellationToken ct) private async Task OnRuntimeInitializeStop(CancellationToken ct) { // Silo may be dying before platformWatchdog was set up - platformWatchdog.Stop(); + platformWatchdog.Stop(); try { @@ -640,5 +640,4 @@ public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILogg { } } -} - +} \ No newline at end of file diff --git a/src/Orleans.Serialization.TestKit/ReadOnlySequenceHelper.cs b/src/Orleans.Serialization.TestKit/ReadOnlySequenceHelper.cs index ce5fe55377..353a823ac3 100644 --- a/src/Orleans.Serialization.TestKit/ReadOnlySequenceHelper.cs +++ b/src/Orleans.Serialization.TestKit/ReadOnlySequenceHelper.cs @@ -46,7 +46,7 @@ public static ReadOnlySequence CreateReadOnlySequence(params byte[][] buff list.Add(buffer); } - return ToReadOnlySequence(list.ToArray()); + return ToReadOnlySequence(list); } private class ReadOnlyBufferSegment : ReadOnlySequenceSegment diff --git a/src/Orleans.Serialization/Serializers/CodecProvider.cs b/src/Orleans.Serialization/Serializers/CodecProvider.cs index 3a3889278d..18b8b5363d 100644 --- a/src/Orleans.Serialization/Serializers/CodecProvider.cs +++ b/src/Orleans.Serialization/Serializers/CodecProvider.cs @@ -2,7 +2,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Orleans.Serialization.Activators; @@ -124,7 +123,7 @@ static void AddFromMetadata(Dictionary resultCollection, HashSet arg.IsGenericParameter)) + if (genericArgument.IsConstructedGenericType && Array.Exists(genericArgument.GenericTypeArguments, arg => arg.IsGenericParameter)) { genericArgument = genericArgument.GetGenericTypeDefinition(); } diff --git a/src/Orleans.Serialization/TypeSystem/TypeConverter.cs b/src/Orleans.Serialization/TypeSystem/TypeConverter.cs index 42dca41002..fac099b76e 100644 --- a/src/Orleans.Serialization/TypeSystem/TypeConverter.cs +++ b/src/Orleans.Serialization/TypeSystem/TypeConverter.cs @@ -173,7 +173,7 @@ void InspectGenericArgument(Type genericArgument) return; } - if (genericArgument.IsConstructedGenericType && genericArgument.GenericTypeArguments.Any(arg => arg.IsGenericParameter)) + if (genericArgument.IsConstructedGenericType && Array.Exists(genericArgument.GenericTypeArguments, arg => arg.IsGenericParameter)) { genericArgument = genericArgument.GetGenericTypeDefinition(); } diff --git a/src/Orleans.TestingHost/InProcessSiloHandle.cs b/src/Orleans.TestingHost/InProcessSiloHandle.cs index 7712db2cbd..5a20320e6c 100644 --- a/src/Orleans.TestingHost/InProcessSiloHandle.cs +++ b/src/Orleans.TestingHost/InProcessSiloHandle.cs @@ -54,7 +54,7 @@ public static async Task CreateAsync( /// public override async Task StopSiloAsync(bool stopGracefully) { - var cancellation = new CancellationTokenSource(); + using var cancellation = new CancellationTokenSource(); var ct = cancellation.Token; if (!stopGracefully) diff --git a/src/Orleans.TestingHost/StandaloneSiloHandle.cs b/src/Orleans.TestingHost/StandaloneSiloHandle.cs index a7cabe2d4e..91309fed1c 100644 --- a/src/Orleans.TestingHost/StandaloneSiloHandle.cs +++ b/src/Orleans.TestingHost/StandaloneSiloHandle.cs @@ -272,7 +272,7 @@ private async Task StartAsync() /// public override async Task StopSiloAsync(bool stopGracefully) { - var cancellation = new CancellationTokenSource(); + using var cancellation = new CancellationTokenSource(); var ct = cancellation.Token; if (!stopGracefully) cancellation.Cancel(); @@ -303,7 +303,7 @@ public override async Task StopSiloAsync(CancellationToken ct) }); await this.Process.StandardInput.WriteLineAsync(StandaloneSiloHost.ShutdownCommand); - var linkedCts = new CancellationTokenSource(); + using var linkedCts = new CancellationTokenSource(); await Task.WhenAny(_runTask, Task.Delay(TimeSpan.FromMinutes(2), linkedCts.Token)); } } diff --git a/src/Orleans.TestingHost/StandaloneSiloHost.cs b/src/Orleans.TestingHost/StandaloneSiloHost.cs index 33aef288ca..bf1dd632b4 100644 --- a/src/Orleans.TestingHost/StandaloneSiloHost.cs +++ b/src/Orleans.TestingHost/StandaloneSiloHost.cs @@ -86,7 +86,7 @@ private static void MonitorParentProcess(int monitorProcessId) while (true) { await Task.Delay(5000); - if (!Process.GetProcesses().Any(p => p.Id == monitorProcessId)) + if (!Array.Exists(Process.GetProcesses(), p => p.Id == monitorProcessId)) { Console.Error.WriteLine($"Parent process {monitorProcessId} has exited"); Environment.Exit(0); diff --git a/src/Orleans.TestingHost/TestCluster.cs b/src/Orleans.TestingHost/TestCluster.cs index b67021df35..2fb90941f1 100644 --- a/src/Orleans.TestingHost/TestCluster.cs +++ b/src/Orleans.TestingHost/TestCluster.cs @@ -492,7 +492,7 @@ public async Task KillClientAsync() var client = ClientHost; if (client != null) { - var cancelled = new CancellationTokenSource(); + using var cancelled = new CancellationTokenSource(); cancelled.Cancel(); try { diff --git a/src/Orleans.TestingHost/Utils/StorageEmulator.cs b/src/Orleans.TestingHost/Utils/StorageEmulator.cs index dbd598ae78..7f65270720 100644 --- a/src/Orleans.TestingHost/Utils/StorageEmulator.cs +++ b/src/Orleans.TestingHost/Utils/StorageEmulator.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Text; namespace Orleans.TestingHost.Utils { @@ -68,13 +69,13 @@ public static string Help() using(var process = Process.Start(CreateProcessArguments("help"))) { process.WaitForExit(); - var help = string.Empty; + StringBuilder help = new(); while(!process.StandardOutput.EndOfStream) { - help += process.StandardOutput.ReadLine(); + help.Append(process.StandardOutput.ReadLine()); } - return help; + return help.ToString(); } } catch (Exception exc) diff --git a/test/DefaultCluster.Tests/AsyncEnumerableGrainCallTests.cs b/test/DefaultCluster.Tests/AsyncEnumerableGrainCallTests.cs index 334038afb9..20322a9b81 100644 --- a/test/DefaultCluster.Tests/AsyncEnumerableGrainCallTests.cs +++ b/test/DefaultCluster.Tests/AsyncEnumerableGrainCallTests.cs @@ -158,7 +158,7 @@ public async Task ObservableGrain_AsyncEnumerable_WithCancellation() }); var values = new List(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); await foreach (var entry in grain.GetValues().WithCancellation(cts.Token)) { values.Add(entry); diff --git a/test/DefaultCluster.Tests/TimerOrleansTest.cs b/test/DefaultCluster.Tests/TimerOrleansTest.cs index 7604fc7d30..d5334f5e1b 100644 --- a/test/DefaultCluster.Tests/TimerOrleansTest.cs +++ b/test/DefaultCluster.Tests/TimerOrleansTest.cs @@ -181,7 +181,7 @@ public async Task GrainTimer_TestAllOverloads() { var grain = GrainFactory.GetGrain(GetRandomGrainId()); - var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var numTimers = await grain.TestAllTimerOverloads(); while (true) { @@ -468,7 +468,7 @@ public async Task GrainTimer_TestAllOverloads_Poco() { var grain = GrainFactory.GetGrain(GetRandomGrainId()); - var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var numTimers = await grain.TestAllTimerOverloads(); while (true) { diff --git a/test/Extensions/AWSUtils.Tests/StorageTests/DynamoDBStorageStressTests.cs b/test/Extensions/AWSUtils.Tests/StorageTests/DynamoDBStorageStressTests.cs index 830130cc03..46611bfdd3 100644 --- a/test/Extensions/AWSUtils.Tests/StorageTests/DynamoDBStorageStressTests.cs +++ b/test/Extensions/AWSUtils.Tests/StorageTests/DynamoDBStorageStressTests.cs @@ -1,4 +1,4 @@ -using Amazon.DynamoDBv2.Model; +using Amazon.DynamoDBv2.Model; using Orleans.TestingHost.Utils; using System.Diagnostics; using System.Globalization; @@ -66,7 +66,7 @@ public void DynamoDBDataManagerStressTests_ReadAll_SinglePartition() var data = manager.QueryAsync(UnitTestDynamoDBStorage.INSTANCE_TABLE_NAME, keys, $"PartitionKey = :PK", item => new UnitTestDynamoDBTableData(item)).Result; sw.Stop(); - int count = data.results.Count(); + int count = data.results.Count; output.WriteLine("DynamoDBDataManagerStressTests_ReadAll completed. ReadAll {0} entries in {1} at {2} RPS", count, sw.Elapsed, count / sw.Elapsed.TotalSeconds); //Assert.True(count >= iterations, $"ReadAllshould return some data: Found={count}"); diff --git a/test/Extensions/ServiceBus.Tests/CollectionFixtures.cs b/test/Extensions/ServiceBus.Tests/CollectionFixtures.cs index 3c78e42282..b2ecee900b 100644 --- a/test/Extensions/ServiceBus.Tests/CollectionFixtures.cs +++ b/test/Extensions/ServiceBus.Tests/CollectionFixtures.cs @@ -25,7 +25,7 @@ public override async Task InitializeAsync() { await base.InitializeAsync(); var collector = new Microsoft.Extensions.Diagnostics.Metrics.Testing.MetricCollector(Instruments.Meter, "orleans-streams-queue-read-duration"); - var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); // Wait for 10 queue read await collector.WaitForMeasurementsAsync(10, cts.Token); } diff --git a/test/Extensions/Tester.Cassandra/Utility/TestExtensions.cs b/test/Extensions/Tester.Cassandra/Utility/TestExtensions.cs index 5a6a2ccd1d..1a1ee8a53c 100644 --- a/test/Extensions/Tester.Cassandra/Utility/TestExtensions.cs +++ b/test/Extensions/Tester.Cassandra/Utility/TestExtensions.cs @@ -10,7 +10,7 @@ public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout) return; } - var timeoutCancellationTokenSource = new CancellationTokenSource(); + using var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); if (taskToComplete == completedTask) @@ -31,7 +31,7 @@ public static async Task WithTimeout(this Task taskToComplete, TimeSpan return await taskToComplete; } - var timeoutCancellationTokenSource = new CancellationTokenSource(); + using var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); if (taskToComplete == completedTask) diff --git a/test/Extensions/Tester.Redis/Utility/TestExtensions.cs b/test/Extensions/Tester.Redis/Utility/TestExtensions.cs index d2e1ce705a..ef203fe918 100644 --- a/test/Extensions/Tester.Redis/Utility/TestExtensions.cs +++ b/test/Extensions/Tester.Redis/Utility/TestExtensions.cs @@ -13,7 +13,7 @@ public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout) return; } - var timeoutCancellationTokenSource = new CancellationTokenSource(); + using var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); if (taskToComplete == completedTask) diff --git a/test/Grains/TestGrains/EventSourcing/ChatFormat.cs b/test/Grains/TestGrains/EventSourcing/ChatFormat.cs index 76fb0baa04..8e0f0571c5 100644 --- a/test/Grains/TestGrains/EventSourcing/ChatFormat.cs +++ b/test/Grains/TestGrains/EventSourcing/ChatFormat.cs @@ -38,8 +38,7 @@ public static XElement FindPost(this XDocument document, string guid) { return document.GetPostsContainer() .Elements("post") - .Where(x => x.Attribute("id").Value == guid) - .FirstOrDefault(); + .FirstOrDefault(x => x.Attribute("id").Value == guid); } public static void ReplaceText(this XElement post, string text) diff --git a/test/NonSilo.Tests/ClientBuilderTests.cs b/test/NonSilo.Tests/ClientBuilderTests.cs index f3d27cfe42..bd39452a88 100644 --- a/test/NonSilo.Tests/ClientBuilderTests.cs +++ b/test/NonSilo.Tests/ClientBuilderTests.cs @@ -194,8 +194,8 @@ public void ClientBuilder_ServiceProviderTest() // Both services should be registered. Assert.Equal(2, services.Count); - Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 1)); - Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 2)); + Assert.NotNull(services.Find(svc => svc.Id == 1)); + Assert.NotNull(services.Find(svc => svc.Id == 2)); // Service 1 should have been registered first - the pipeline order should be preserved. Assert.Equal(1, registeredFirst[0]); diff --git a/test/NonSilo.Tests/General/RingTests_Standalone.cs b/test/NonSilo.Tests/General/RingTests_Standalone.cs index 97fc2738ec..98d4ab494e 100644 --- a/test/NonSilo.Tests/General/RingTests_Standalone.cs +++ b/test/NonSilo.Tests/General/RingTests_Standalone.cs @@ -266,7 +266,7 @@ public bool TryGetSiloName(SiloAddress siloAddress, out string siloName) internal class RangeBreakable { private List ranges { get; set; } - internal int NumRanges { get { return ranges.Count(); } } + internal int NumRanges { get { return ranges.Count; } } public RangeBreakable() { diff --git a/test/NonSilo.Tests/Membership/InMemoryMembershipTable.cs b/test/NonSilo.Tests/Membership/InMemoryMembershipTable.cs index 6705bae75c..15e22fccf5 100644 --- a/test/NonSilo.Tests/Membership/InMemoryMembershipTable.cs +++ b/test/NonSilo.Tests/Membership/InMemoryMembershipTable.cs @@ -102,7 +102,7 @@ public Task InsertRow(MembershipEntry entry, TableVersion tableVersion) this.calls.Add((nameof(InsertRow), (entry, tableVersion))); this.ValidateVersion(tableVersion); - if (this.entries.Any(e => e.Item1.SiloAddress.Equals(entry.SiloAddress))) + if (this.entries.Exists(e => e.Item1.SiloAddress.Equals(entry.SiloAddress))) { return Task.FromResult(false); } @@ -158,7 +158,7 @@ public Task UpdateRow(MembershipEntry entry, string etag, TableVersion tab { this.calls.Add((nameof(UpdateRow), (entry, etag, tableVersion))); this.ValidateVersion(tableVersion); - var existingEntry = this.entries.FirstOrDefault(e => e.Item1.SiloAddress.Equals(entry.SiloAddress)); + var existingEntry = this.entries.Find(e => e.Item1.SiloAddress.Equals(entry.SiloAddress)); if (existingEntry.Item1 is null) return Task.FromResult(false); if (!etag.Equals(existingEntry.Item2)) diff --git a/test/NonSilo.Tests/Membership/MembershipAgentTests.cs b/test/NonSilo.Tests/Membership/MembershipAgentTests.cs index ad8b78ba65..c7a1403abc 100644 --- a/test/NonSilo.Tests/Membership/MembershipAgentTests.cs +++ b/test/NonSilo.Tests/Membership/MembershipAgentTests.cs @@ -192,7 +192,7 @@ Func Callback(int level) => ct => Assert.Equal(SiloStatus.Joining, levels[ServiceLifecycleStage.AfterRuntimeGrainServices + 1]); Assert.Equal(SiloStatus.Active, levels[ServiceLifecycleStage.BecomeActive + 1]); - var cancellation = new CancellationTokenSource(); + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await StopLifecycle(cancellation.Token); diff --git a/test/NonSilo.Tests/Membership/MembershipTableManagerTests.cs b/test/NonSilo.Tests/Membership/MembershipTableManagerTests.cs index 59f4b10bdd..2942f2b744 100644 --- a/test/NonSilo.Tests/Membership/MembershipTableManagerTests.cs +++ b/test/NonSilo.Tests/Membership/MembershipTableManagerTests.cs @@ -172,7 +172,7 @@ private async Task BasicScenarioTest(InMemoryMembershipTable membershipTable, bo Assert.Contains(membershipTable.Calls, c => c.Method.Equals(nameof(IMembershipTable.ReadAll))); } - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); if (!gracefulShutdown) cts.Cancel(); Assert.Equal(0, timers.First().DisposedCounter); var stopped = this.lifecycle.OnStop(cts.Token); @@ -361,7 +361,7 @@ public async Task MembershipTableManager_AlreadyDeclaredDead() this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); await this.lifecycle.OnStop(cts.Token); } diff --git a/test/Tester/Forwarding/ShutdownSiloTests.cs b/test/Tester/Forwarding/ShutdownSiloTests.cs index d240280f6a..65b9019c3b 100644 --- a/test/Tester/Forwarding/ShutdownSiloTests.cs +++ b/test/Tester/Forwarding/ShutdownSiloTests.cs @@ -113,7 +113,7 @@ public async Task SiloGracefulShutdown_StuckActivation() await Task.Delay(500); var stopwatch = Stopwatch.StartNew(); - var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await HostedCluster.SecondarySilos.First().StopSiloAsync(cts.Token); stopwatch.Stop(); Assert.True(stopwatch.Elapsed < TimeSpan.FromMinutes(1)); diff --git a/test/Tester/LocalhostSiloTests.cs b/test/Tester/LocalhostSiloTests.cs index 3559f93deb..ee479b895d 100644 --- a/test/Tester/LocalhostSiloTests.cs +++ b/test/Tester/LocalhostSiloTests.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Orleans.Internal; -using Orleans.Runtime; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using Xunit; @@ -88,11 +87,11 @@ public async Task LocalhostClusterTest() } finally { - var cancelled = new CancellationTokenSource(); + using var cancelled = new CancellationTokenSource(); cancelled.Cancel(); - Utils.SafeExecute(() => silo1.StopAsync(cancelled.Token)); - Utils.SafeExecute(() => silo2.StopAsync(cancelled.Token)); - Utils.SafeExecute(() => clientHost.StopAsync(cancelled.Token)); + await Utils.SafeExecuteAsync(silo1.StopAsync(cancelled.Token)); + await Utils.SafeExecuteAsync(silo2.StopAsync(cancelled.Token)); + await Utils.SafeExecuteAsync(clientHost.StopAsync(cancelled.Token)); Utils.SafeExecute(() => silo1.Dispose()); Utils.SafeExecute(() => silo2.Dispose()); Utils.SafeExecute(() => clientHost.Dispose()); diff --git a/test/Tester/StreamingTests/BroadcastChannels/BroadcastChannelTests.cs b/test/Tester/StreamingTests/BroadcastChannels/BroadcastChannelTests.cs index 8cc5c0db90..8d654b7600 100644 --- a/test/Tester/StreamingTests/BroadcastChannels/BroadcastChannelTests.cs +++ b/test/Tester/StreamingTests/BroadcastChannels/BroadcastChannelTests.cs @@ -188,7 +188,7 @@ private async Task MultipleSubscribersOneBadActorChannelTestImpl(IBroadcastChann await stream.Publish(2); // Wait to be sure that published event reached the grain var counter = 0; - var cts = new CancellationTokenSource(CallTimeoutMs); + using var cts = new CancellationTokenSource(CallTimeoutMs); while (!cts.IsCancellationRequested) { counter = await badGrain.GetOnPublishedCounter(); @@ -238,7 +238,7 @@ private async Task MultipleSubscribersOneBadActorChannelTestImpl(IBroadcastChann private static async Task> Get(Func>> func, int expectedCount, int timeoutMs = CallTimeoutMs) { - var cts = new CancellationTokenSource(timeoutMs); + using var cts = new CancellationTokenSource(timeoutMs); while (!cts.IsCancellationRequested) { try diff --git a/test/TesterInternal/StreamingTests/StreamPubSubReliabilityTests.cs b/test/TesterInternal/StreamingTests/StreamPubSubReliabilityTests.cs index 21a621d4fc..133538ff89 100644 --- a/test/TesterInternal/StreamingTests/StreamPubSubReliabilityTests.cs +++ b/test/TesterInternal/StreamingTests/StreamPubSubReliabilityTests.cs @@ -116,7 +116,7 @@ private async Task Test_PubSub_Stream(string streamProviderName, Guid streamId) await producer.SendItem(1); int received1 = 0; - var cts = new CancellationTokenSource(1000); + using var cts = new CancellationTokenSource(1000); do { received1 = await consumer.GetReceivedCount();