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

Fix all IDE0039 warnings, prefer local functions #8605

Merged
merged 1 commit into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions src/Azure/Shared/Storage/AzureTableDataManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ public async Task DeleteTableEntriesAsync(List<(T Entity, string ETag)> collecti

try
{
Func<Task<List<(T Entity, string ETag)>>> executeQueryHandleContinuations = async () =>
async Task<List<(T Entity, string ETag)>> executeQueryHandleContinuations()
{
var list = new List<(T, string)>();
var results = Table.QueryAsync<T>(filter);
Expand All @@ -520,7 +520,7 @@ public async Task DeleteTableEntriesAsync(List<(T Entity, string ETag)> collecti
}

return list;
};
}

#if !ORLEANS_TRANSACTIONS
IBackoffProvider backoff = new FixedBackoff(this.StoragePolicyOptions.PauseBetweenOperationRetries);
Expand Down
2 changes: 1 addition & 1 deletion src/Orleans.Core/Async/AsyncExecutorWithRetries.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static Task ExecuteWithRetries(
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
Func<int, Task<bool>> function = async (int i) => { await action(i); return true; };
async Task<bool> function(int i) { await action(i); return true; }
return ExecuteWithRetriesHelper<bool>(
function,
0,
Expand Down
2 changes: 1 addition & 1 deletion src/Orleans.Runtime/Catalog/ActivationCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ private async Task DeactivateActivationsFromCollector(List<ICollectibleGrainCont
logger.LogInformation((int)ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {Count} to promptly Destroy.", list.Count);
CatalogInstruments.ActiviationShutdownViaCollection();

Action<Task> signalCompletion = task => mtcs.SetOneResult();
void signalCompletion(Task task) => mtcs.SetOneResult();
Copy link
Contributor

Choose a reason for hiding this comment

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

This one should be reverted - it's going to cause potentially multiple delegate allocations (one for each list item, instead of one overall).

var reason = GetDeactivationReason();
for (var i = 0; i < list.Count; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,13 +318,13 @@ public async Task UpdateStatus(SiloStatus status)

try
{
Func<int, Task<bool>> updateMyStatusTask = async counter =>
async Task<bool> updateMyStatusTask(int counter)
{
numCalls++;
if (log.IsEnabled(LogLevel.Debug)) log.LogDebug("Going to try to TryUpdateMyStatusGlobalOnce #{Attempt}", counter);
return await TryUpdateMyStatusGlobalOnce(status); // function to retry
};
}

if (status == SiloStatus.Dead && this.membershipTableProvider is SystemTargetBasedMembershipTable)
{
// SystemTarget-based membership may not be accessible at this stage, so allow for one quick attempt to update
Expand Down
25 changes: 12 additions & 13 deletions src/Orleans.TestingHost/Utils/TestingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,19 @@ public static async Task WaitUntilAsync(Func<bool,Task<bool>> predicate, TimeSpa
{
delayOnFail = delayOnFail ?? TimeSpan.FromSeconds(1);
var keepGoing = new[] { true };
Func<Task> loop =
async () =>
async Task loop()
{
bool passed;
do
{
bool passed;
do
{
// need to wait a bit to before re-checking the condition.
await Task.Delay(delayOnFail.Value);
passed = await predicate(false);
}
while (!passed && keepGoing[0]);
if(!passed)
await predicate(true);
};
// need to wait a bit to before re-checking the condition.
await Task.Delay(delayOnFail.Value);
passed = await predicate(false);
}
while (!passed && keepGoing[0]);
if (!passed)
await predicate(true);
}

var task = loop();
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,14 @@ public void CheckConsistency(bool tolerateGenericTimeouts = false, bool tolerate
foreach (var grainKvp in tuples)
{
var pos = 0;
Action<string> fail = (msg) =>
void fail(string msg)
{
foreach (var kvp1 in grainKvp.Value)
foreach (var kvp2 in kvp1.Value)
foreach (var r in kvp2.Value)
output($"g{grainKvp.Key} v{kvp1.Key} w:{kvp2.Key} a:{r}");
true.Should().BeFalse(msg);
};
}

HashSet<string> readersOfPreviousVersion = new HashSet<string>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ protected virtual async Task TransactionWillRecoverAfterRandomSiloFailure(string
{
var endOnCommand = new[] { false };
var index = new[] { 0 };
Func<int> getIndex = () => index[0]++;
int getIndex() => index[0]++;
List<ExpectedGrainActivity> txGrains = Enumerable.Range(0, concurrent * 2)
.Select(i => Guid.NewGuid())
.Select(grainId => new ExpectedGrainActivity(grainId, TestGrain<ITransactionalBitArrayGrain>(transactionTestGrainClassName, grainId)))
Expand Down
4 changes: 2 additions & 2 deletions src/Orleans.Transactions/State/ReaderWriterLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public async Task<TResult> EnterLock<TResult>(Guid transactionId, DateTime prior

var result =
new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
Action completion = () =>
void completion()
{
try
{
Expand All @@ -148,7 +148,7 @@ public async Task<TResult> EnterLock<TResult>(Guid transactionId, DateTime prior
{
result.TrySetException(exception);
}
};
}

if (group != currentGroup)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Orleans.Transactions/State/TransactionalState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ internal async Task OnSetupState(Action<IGrainContext, string, TransactionQueue<
ITransactionalStateStorage<TState> storage = storageFactory.Create<TState>(this.config.StorageName, this.config.StateName);

// setup transaction processing pipe
Action deactivate = () => grainRuntime.DeactivateOnIdle(context);
void deactivate() => grainRuntime.DeactivateOnIdle(context);
var options = this.context.ActivationServices.GetRequiredService<IOptions<TransactionalStateOptions>>();
var clock = this.context.ActivationServices.GetRequiredService<IClock>();
var timerManager = this.context.ActivationServices.GetRequiredService<ITimerManager>();
Expand Down
2 changes: 1 addition & 1 deletion src/Orleans.Transactions/TOC/TransactionCommitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ private async Task OnSetupState(CancellationToken ct)
ITransactionalStateStorage<OperationState> storage = storageFactory.Create<OperationState>(this.config.StorageName, this.config.ServiceName);

// setup transaction processing pipe
Action deactivate = () => grainRuntime.DeactivateOnIdle(context);
void deactivate() => grainRuntime.DeactivateOnIdle(context);
var options = this.context.ActivationServices.GetRequiredService<IOptions<TransactionalStateOptions>>();
var clock = this.context.ActivationServices.GetRequiredService<IClock>();
TService service = this.context.ActivationServices.GetRequiredServiceByName<TService>(this.config.ServiceName);
Expand Down
2 changes: 1 addition & 1 deletion test/Benchmarks/GrainStorage/GrainStorageBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public async Task RunAsync()
{
Stopwatch sw = Stopwatch.StartNew();
bool running = true;
Func<bool> isRunning = () => running;
bool isRunning() => running;
var runTask = Task.WhenAll(Enumerable.Range(0, concurrent).Select(i => RunAsync(i, isRunning)).ToList());
Task[] waitTasks = { runTask, Task.Delay(duration) };
await Task.WhenAny(waitTasks);
Expand Down
4 changes: 2 additions & 2 deletions test/Extensions/Consul.Tests/ConsulClusteringOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void ThrowsArgumentNullExceptionIfCallbackIsNull()
Func<IConsulClient> callback = null;

// ensure we check the callback.
var shouldThrow = ()=> options.ConfigureConsulClient(callback);
void shouldThrow() => options.ConfigureConsulClient(callback);

Assert.Throws<ArgumentNullException>(shouldThrow);
}
Expand All @@ -36,7 +36,7 @@ public void WeCanInjectAConsulClient()
{
var fakeConsul = new FakeConsul();
var options = new ConsulClusteringOptions();
Func<IConsulClient> callback = () => fakeConsul;
IConsulClient callback() => fakeConsul;

//we can inject the consul
options.ConfigureConsulClient(callback);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ protected override IEventHubQueueCacheFactory CreateCacheFactory(EventHubStreamC
var loggerFactory = this.serviceProvider.GetRequiredService<ILoggerFactory>();
var eventHubPath = this.ehOptions.EventHubName;
var sharedDimensions = new EventHubMonitorAggregationDimensions(eventHubPath);
Func<EventHubCacheMonitorDimensions, ILoggerFactory, ICacheMonitor> cacheMonitorFactory = (dimensions, logger) => this.cacheMonitorForTesting;
Func<EventHubBlockPoolMonitorDimensions, ILoggerFactory, IBlockPoolMonitor> blockPoolMonitorFactory = (dimensions, logger) => this.blockPoolMonitorForTesting;
ICacheMonitor cacheMonitorFactory(EventHubCacheMonitorDimensions dimensions, ILoggerFactory logger) => this.cacheMonitorForTesting;
IBlockPoolMonitor blockPoolMonitorFactory(EventHubBlockPoolMonitorDimensions dimensions, ILoggerFactory logger) => this.blockPoolMonitorForTesting;
return new CacheFactoryForMonitorTesting(
this.cachePressureInjectionMonitor,
this.cacheOptions,
Expand Down
51 changes: 24 additions & 27 deletions test/Extensions/TesterAzureUtils/AsyncPipelineTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,37 +114,34 @@ private async Task AsyncPipelineBlackBoxConsistencyTest(int workerCount)
int[] pipelineSize = { 0 };
var capacityReached = new InterlockedFlag();

Action workFunc =
() =>
{
var sz = Interlocked.Increment(ref pipelineSize[0]);
CheckPipelineState(sz, pipelineCapacity, capacityReached);
Task.Delay(delayLength).Wait();
Interlocked.Decrement(ref pipelineSize[0]);
Interlocked.Increment(ref tasksCompleted);
};
void workFunc()
{
var sz = Interlocked.Increment(ref pipelineSize[0]);
CheckPipelineState(sz, pipelineCapacity, capacityReached);
Task.Delay(delayLength).Wait();
Interlocked.Decrement(ref pipelineSize[0]);
Interlocked.Increment(ref tasksCompleted);
}

Action workerFunc =
() =>
void workerFunc()
{
for (var j = 0; j < loopCount; j++)
{
for (var j = 0; j < loopCount; j++)
{
Task task = new Task(workFunc);
pipeline.Add(task, whiteBox: null);
task.Start();
}
};
Task task = new Task(workFunc);
pipeline.Add(task, whiteBox: null);
task.Start();
}
}

Func<Task> monitorFunc =
async () =>
async Task monitorFunc()
{
var delay = TimeSpan.FromSeconds(5);
while (tasksCompleted < expectedTasksCompleted)
{
var delay = TimeSpan.FromSeconds(5);
while (tasksCompleted < expectedTasksCompleted)
{
output.WriteLine("test in progress: tasksCompleted = {0}.", tasksCompleted);
await Task.Delay(delay);
}
};
output.WriteLine("test in progress: tasksCompleted = {0}.", tasksCompleted);
await Task.Delay(delay);
}
}

var workers = new Task[workerCount];
var stopwatch = Stopwatch.StartNew();
Expand Down
49 changes: 24 additions & 25 deletions test/Grains/TestInternalGrains/ActivateDeactivateTestGrain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,37 +247,36 @@ public override async Task OnActivateAsync(CancellationToken cancellationToken)
});
// we want to use Task.ContinueWith with an async lambda, an explicitly typed variable is required to avoid
// writing code that doesn't do what i think it is doing.
Func<Task> asyncCont =
async () =>
{
Assert.NotNull(TaskScheduler.Current);
Assert.NotEqual(TaskScheduler.Current, TaskScheduler.Default);
logger.LogInformation("Started-OnActivateAsync");
async Task asyncCont()
{
Assert.NotNull(TaskScheduler.Current);
Assert.NotEqual(TaskScheduler.Current, TaskScheduler.Default);
logger.LogInformation("Started-OnActivateAsync");

Assert.True(doingActivate, "Doing Activate 1");
Assert.False(doingDeactivate, "Not doing Deactivate");
Assert.True(doingActivate, "Doing Activate 1");
Assert.False(doingDeactivate, "Not doing Deactivate");

try
{
logger.LogInformation("Calling RecordActivateCall");
await watcher.RecordActivateCall(RuntimeHelpers.GetHashCode(this).ToString("X"));
logger.LogInformation("Returned from calling RecordActivateCall");
}
catch (Exception exc)
{
logger.LogError(exc, "RecordActivateCall failed");
Assert.True(false, "RecordActivateCall failed with error " + exc);
}
try
{
logger.LogInformation("Calling RecordActivateCall");
await watcher.RecordActivateCall(RuntimeHelpers.GetHashCode(this).ToString("X"));
logger.LogInformation("Returned from calling RecordActivateCall");
}
catch (Exception exc)
{
logger.LogError(exc, "RecordActivateCall failed");
Assert.True(false, "RecordActivateCall failed with error " + exc);
}

Assert.True(doingActivate, "Doing Activate 2");
Assert.False(doingDeactivate, "Not doing Deactivate");
Assert.True(doingActivate, "Doing Activate 2");
Assert.False(doingDeactivate, "Not doing Deactivate");

await Task.Delay(TimeSpan.FromSeconds(1));
await Task.Delay(TimeSpan.FromSeconds(1));

doingActivate = false;
doingActivate = false;

logger.LogInformation("Finished-OnActivateAsync");
};
logger.LogInformation("Finished-OnActivateAsync");
}
var awaitMe = startMe.ContinueWith(_ => asyncCont()).Unwrap();
startMe.Start();
await awaitMe;
Expand Down
8 changes: 4 additions & 4 deletions test/Grains/TestInternalGrains/StreamingGrain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,10 @@ public Task ProduceParallelSeries(int count)
for (var i = 1; i <= count; ++i)
{
int capture = i;
Func<Task<bool>> func = async () =>
{
return await ProduceItem($"parallel#{capture}");
};
async Task<bool> func()
{
return await ProduceItem($"parallel#{capture}");
}
// Need to call on different threads to force parallel execution.
tasks[capture - 1] = Task.Factory.StartNew(func).Unwrap();
}
Expand Down
6 changes: 3 additions & 3 deletions test/NonSilo.Tests/Membership/MembershipAgentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ Func<CancellationToken, Task> Callback(int level) => ct =>
levels[level] = this.manager.CurrentStatus;
return Task.CompletedTask;
};
Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask;
Task NoOp(CancellationToken ct) => Task.CompletedTask;
foreach (var l in new[] {
ServiceLifecycleStage.RuntimeInitialize,
ServiceLifecycleStage.AfterRuntimeGrainServices,
Expand Down Expand Up @@ -171,7 +171,7 @@ Func<CancellationToken, Task> Callback(int level) => ct =>
levels[level] = this.manager.CurrentStatus;
return Task.CompletedTask;
};
Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask;
Task NoOp(CancellationToken ct) => Task.CompletedTask;
foreach (var l in new[] {
ServiceLifecycleStage.RuntimeInitialize,
ServiceLifecycleStage.AfterRuntimeGrainServices,
Expand Down Expand Up @@ -271,7 +271,7 @@ public async Task MembershipAgent_LifecycleStages_ValidateInitialConnectivity_Su
Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next()));
}

Func<SiloHealthMonitor, SiloHealthMonitor.ProbeResult, Task> onProbeResult = (siloHealthMonitor, probeResult) => Task.CompletedTask;
Task onProbeResult(SiloHealthMonitor siloHealthMonitor, SiloHealthMonitor.ProbeResult probeResult) => Task.CompletedTask;

var clusterHealthMonitorTestAccessor = (ClusterHealthMonitor.ITestAccessor)this.clusterHealthMonitor;
clusterHealthMonitorTestAccessor.CreateMonitor = silo => new SiloHealthMonitor(
Expand Down
2 changes: 1 addition & 1 deletion test/NonSilo.Tests/Membership/SiloHealthMonitorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public SiloHealthMonitorTests(ITestOutputHelper output)
_optionsMonitor.CurrentValue.ReturnsForAnyArgs(info => _clusterMembershipOptions);

_probeResults = Channel.CreateBounded<ProbeResult>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.Wait });
Func<SiloHealthMonitor, ProbeResult, Task> onProbeResult = (mon, res) => _probeResults.Writer.WriteAsync(res).AsTask();
Task onProbeResult(SiloHealthMonitor mon, ProbeResult res) => _probeResults.Writer.WriteAsync(res).AsTask();

_membershipSnapshot = Snapshot(
1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public void ActivationSched_SubTaskExecutionSequencing()

int n = 0;

Action action = () =>
void action()
{
LogContext("WorkItem-task " + Task.CurrentId);

Expand All @@ -134,7 +134,7 @@ public void ActivationSched_SubTaskExecutionSequencing()
this.output.WriteLine("Sub-task " + id + " Done");
});
}
};
}

Task t = new Task(action);

Expand Down Expand Up @@ -705,7 +705,7 @@ internal async Task Run_ActivationSched_Test1(TaskScheduler scheduler, bool boun

Task t1 = grain.Test1();

Action wrappedDoneAction = () => { wrappedDone.SetResult(true); };
void wrappedDoneAction() { wrappedDone.SetResult(true); }

if (bounceToThreadPool)
{
Expand Down
Loading