Skip to content

Resolve ide0040, ide0051, ide0052, ide0350 warnings #11740

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

Merged
merged 2 commits into from
Apr 22, 2025
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
2 changes: 1 addition & 1 deletion src/Build/BackEnd/BuildManager/BuildManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2405,7 +2405,7 @@ private void HandleResourceRequest(int node, ResourceRequest request)
{
// Resource request requires a response and may be blocking. Our continuation is effectively a callback
// to be called once at least one core becomes available.
_scheduler!.RequestCores(request.GlobalRequestId, request.NumCores, request.IsBlocking).ContinueWith((Task<int> task) =>
_scheduler!.RequestCores(request.GlobalRequestId, request.NumCores, request.IsBlocking).ContinueWith((task) =>
{
var response = new ResourceResponse(request.GlobalRequestId, task.Result);
_nodeManager!.SendData(node, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -881,23 +881,6 @@ public async Task WaitForExitAsync(ILoggingService loggingService)
_process.KillTree(timeoutMilliseconds: 5000);
}

#if FEATURE_APM
/// <summary>
/// Completes the asynchronous packet write to the node.
/// </summary>
private void PacketWriteComplete(IAsyncResult result)
{
try
{
_serverToClientStream.EndWrite(result);
}
catch (IOException)
{
// Do nothing here because any exception will be caught by the async read handler
}
}
#endif

private bool ProcessHeaderBytesRead(int bytesRead)
{
if (bytesRead != _headerByte.Length)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ public int RequestCores(object monitorLockObject, int requestedCores, bool waitF
// a queue of pending requests.
ResourceResponse responseObject = null;
using AutoResetEvent responseEvent = new AutoResetEvent(false);
_pendingResourceRequests.Enqueue((ResourceResponse response) =>
_pendingResourceRequests.Enqueue((response) =>
{
responseObject = response;
responseEvent.Set();
Expand Down
53 changes: 19 additions & 34 deletions src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,6 @@ internal class TargetEntry : IEquatable<TargetEntry>
/// </summary>
private bool _isExecuting;

/// <summary>
/// The current task builder.
/// </summary>
private ITaskBuilder _currentTaskBuilder;

/// <summary>
/// The constructor.
/// </summary>
Expand Down Expand Up @@ -816,46 +811,36 @@ private async ValueTask<WorkUnitResult> ProcessBucket(ITaskBuilder taskBuilder,
WorkUnitActionCode finalActionCode = WorkUnitActionCode.Continue;
WorkUnitResult lastResult = new WorkUnitResult(WorkUnitResultCode.Success, WorkUnitActionCode.Continue, null);

try
int currentTask = 0;

// Walk through all of the tasks and execute them in order.
for (; (currentTask < _target.Children.Count) && !_cancellationToken.IsCancellationRequested; ++currentTask)
{
// Grab the task builder so if cancel is called it will have something to operate on.
_currentTaskBuilder = taskBuilder;
ProjectTargetInstanceChild targetChildInstance = _target.Children[currentTask];

int currentTask = 0;
// Execute the task.
lastResult = await taskBuilder.ExecuteTask(targetLoggingContext, _requestEntry, _targetBuilderCallback, targetChildInstance, mode, lookupForInference, lookupForExecution, _cancellationToken);

// Walk through all of the tasks and execute them in order.
for (; (currentTask < _target.Children.Count) && !_cancellationToken.IsCancellationRequested; ++currentTask)
if (lastResult.ResultCode == WorkUnitResultCode.Failed)
{
ProjectTargetInstanceChild targetChildInstance = _target.Children[currentTask];

// Execute the task.
lastResult = await taskBuilder.ExecuteTask(targetLoggingContext, _requestEntry, _targetBuilderCallback, targetChildInstance, mode, lookupForInference, lookupForExecution, _cancellationToken);

if (lastResult.ResultCode == WorkUnitResultCode.Failed)
{
aggregatedTaskResult = WorkUnitResultCode.Failed;
}
else if (lastResult.ResultCode == WorkUnitResultCode.Success && aggregatedTaskResult != WorkUnitResultCode.Failed)
{
aggregatedTaskResult = WorkUnitResultCode.Success;
}

if (lastResult.ActionCode == WorkUnitActionCode.Stop)
{
finalActionCode = WorkUnitActionCode.Stop;
break;
}
aggregatedTaskResult = WorkUnitResultCode.Failed;
}
else if (lastResult.ResultCode == WorkUnitResultCode.Success && aggregatedTaskResult != WorkUnitResultCode.Failed)
{
aggregatedTaskResult = WorkUnitResultCode.Success;
}

if (_cancellationToken.IsCancellationRequested)
if (lastResult.ActionCode == WorkUnitActionCode.Stop)
{
aggregatedTaskResult = WorkUnitResultCode.Canceled;
finalActionCode = WorkUnitActionCode.Stop;
break;
}
}
finally

if (_cancellationToken.IsCancellationRequested)
{
_currentTaskBuilder = null;
aggregatedTaskResult = WorkUnitResultCode.Canceled;
finalActionCode = WorkUnitActionCode.Stop;
}

return new WorkUnitResult(aggregatedTaskResult, finalActionCode, lastResult.Exception);
Expand Down
4 changes: 2 additions & 2 deletions src/Build/BackEnd/Components/Scheduler/Scheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ public Task<int> RequestCores(int requestId, int requestedCores, bool waitForCor
return Task.FromResult(0);
}

Func<int, int> grantCores = (int availableCores) =>
Func<int, int> grantCores = (availableCores) =>
{
int grantedCores = Math.Min(requestedCores, availableCores);
if (grantedCores > 0)
Expand All @@ -599,7 +599,7 @@ public Task<int> RequestCores(int requestId, int requestedCores, bool waitForCor
// We have no cores to grant at the moment, queue up the request.
TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>();
_pendingRequestCoresCallbacks.Enqueue(completionSource);
return completionSource.Task.ContinueWith((Task<int> task) => grantCores(task.Result), TaskContinuationOptions.ExecuteSynchronously);
return completionSource.Task.ContinueWith((task) => grantCores(task.Result), TaskContinuationOptions.ExecuteSynchronously);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Build/BackEnd/Components/Scheduler/SchedulingPlan.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public void WritePlan(int submissionId, ILoggingService loggingService, BuildEve
RecursiveAccumulateConfigurationTimes(rootRequest, accumulatedTimeByConfiguration);

List<KeyValuePair<int, double>> configurationsInOrder = new(accumulatedTimeByConfiguration);
configurationsInOrder.Sort((KeyValuePair<int, double> l, KeyValuePair<int, double> r) => Comparer<int>.Default.Compare(l.Key, r.Key));
configurationsInOrder.Sort((l, r) => Comparer<int>.Default.Compare(l.Key, r.Key));
foreach (KeyValuePair<int, double> configuration in configurationsInOrder)
{
file.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", configuration.Key, configuration.Value, _configCache[configuration.Key].ProjectFullPath));
Expand Down
28 changes: 14 additions & 14 deletions src/Build/BuildCheck/Infrastructure/BuildCheckBuildEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,25 @@ internal BuildCheckBuildEventHandler(

_eventHandlersFull = new()
{
{ typeof(BuildSubmissionStartedEventArgs), (BuildEventArgs e) => HandleBuildSubmissionStartedEvent((BuildSubmissionStartedEventArgs)e) },
{ typeof(ProjectEvaluationFinishedEventArgs), (BuildEventArgs e) => HandleProjectEvaluationFinishedEvent((ProjectEvaluationFinishedEventArgs)e) },
{ typeof(ProjectEvaluationStartedEventArgs), (BuildEventArgs e) => HandleProjectEvaluationStartedEvent((ProjectEvaluationStartedEventArgs)e) },
{ typeof(EnvironmentVariableReadEventArgs), (BuildEventArgs e) => HandleEnvironmentVariableReadEvent((EnvironmentVariableReadEventArgs)e) },
{ typeof(ProjectStartedEventArgs), (BuildEventArgs e) => HandleProjectStartedRequest((ProjectStartedEventArgs)e) },
{ typeof(ProjectFinishedEventArgs), (BuildEventArgs e) => HandleProjectFinishedRequest((ProjectFinishedEventArgs)e) },
{ typeof(BuildCheckTracingEventArgs), (BuildEventArgs e) => HandleBuildCheckTracingEvent((BuildCheckTracingEventArgs)e) },
{ typeof(BuildCheckAcquisitionEventArgs), (BuildEventArgs e) => HandleBuildCheckAcquisitionEvent((BuildCheckAcquisitionEventArgs)e) },
{ typeof(TaskStartedEventArgs), (BuildEventArgs e) => HandleTaskStartedEvent((TaskStartedEventArgs)e) },
{ typeof(TaskFinishedEventArgs), (BuildEventArgs e) => HandleTaskFinishedEvent((TaskFinishedEventArgs)e) },
{ typeof(TaskParameterEventArgs), (BuildEventArgs e) => HandleTaskParameterEvent((TaskParameterEventArgs)e) },
{ typeof(BuildFinishedEventArgs), (BuildEventArgs e) => HandleBuildFinishedEvent((BuildFinishedEventArgs)e) },
{ typeof(ProjectImportedEventArgs), (BuildEventArgs e) => HandleProjectImportedEvent((ProjectImportedEventArgs)e) },
{ typeof(BuildSubmissionStartedEventArgs), (e) => HandleBuildSubmissionStartedEvent((BuildSubmissionStartedEventArgs)e) },
{ typeof(ProjectEvaluationFinishedEventArgs), (e) => HandleProjectEvaluationFinishedEvent((ProjectEvaluationFinishedEventArgs)e) },
{ typeof(ProjectEvaluationStartedEventArgs), (e) => HandleProjectEvaluationStartedEvent((ProjectEvaluationStartedEventArgs)e) },
{ typeof(EnvironmentVariableReadEventArgs), (e) => HandleEnvironmentVariableReadEvent((EnvironmentVariableReadEventArgs)e) },
{ typeof(ProjectStartedEventArgs), (e) => HandleProjectStartedRequest((ProjectStartedEventArgs)e) },
{ typeof(ProjectFinishedEventArgs), (e) => HandleProjectFinishedRequest((ProjectFinishedEventArgs)e) },
{ typeof(BuildCheckTracingEventArgs), (e) => HandleBuildCheckTracingEvent((BuildCheckTracingEventArgs)e) },
{ typeof(BuildCheckAcquisitionEventArgs), (e) => HandleBuildCheckAcquisitionEvent((BuildCheckAcquisitionEventArgs)e) },
{ typeof(TaskStartedEventArgs), (e) => HandleTaskStartedEvent((TaskStartedEventArgs)e) },
{ typeof(TaskFinishedEventArgs), (e) => HandleTaskFinishedEvent((TaskFinishedEventArgs)e) },
{ typeof(TaskParameterEventArgs), (e) => HandleTaskParameterEvent((TaskParameterEventArgs)e) },
{ typeof(BuildFinishedEventArgs), (e) => HandleBuildFinishedEvent((BuildFinishedEventArgs)e) },
{ typeof(ProjectImportedEventArgs), (e) => HandleProjectImportedEvent((ProjectImportedEventArgs)e) },
};

// During restore we'll wait only for restore to be done.
_eventHandlersRestore = new()
{
{ typeof(BuildSubmissionStartedEventArgs), (BuildEventArgs e) => HandleBuildSubmissionStartedEvent((BuildSubmissionStartedEventArgs)e) },
{ typeof(BuildSubmissionStartedEventArgs), (e) => HandleBuildSubmissionStartedEvent((BuildSubmissionStartedEventArgs)e) },
};

_eventHandlers = _eventHandlersFull;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,11 @@ namespace Microsoft.Build.Experimental.BuildCheck.Infrastructure;
internal sealed class BuildCheckConnectorLogger : ILogger
{
private readonly BuildCheckBuildEventHandler _eventHandler;
private readonly IBuildCheckManager _buildCheckManager;
private readonly ICheckContextFactory _checkContextFactory;

internal BuildCheckConnectorLogger(
ICheckContextFactory checkContextFactory,
IBuildCheckManager buildCheckManager)
{
_buildCheckManager = buildCheckManager;
_checkContextFactory = checkContextFactory;
_eventHandler = new BuildCheckBuildEventHandler(checkContextFactory, buildCheckManager);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Build/BuildCheck/OM/BuildCheckDataContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public abstract class CheckData(string projectFilePath, int? projectConfiguratio
{
private string? _projectFileDirectory;
// The id is going to be used in future revision
#pragma warning disable CA1823
#pragma warning disable CA1823, IDE0052
private int? _projectConfigurationId = projectConfigurationId;
#pragma warning restore CA1823
#pragma warning restore CA1823, IDE0052

/// <summary>
/// Full path to the project file being built.
Expand Down
2 changes: 1 addition & 1 deletion src/Build/Definition/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3815,7 +3815,7 @@ internal void Initialize(IDictionary<string, string> globalProperties, string to

// Cause the project to be actually loaded into the collection, and register for
// rename notifications so we can subsequently update the collection.
_renameHandler = (string oldFullPath) => ProjectCollection.OnAfterRenameLoadedProject(oldFullPath, Owner);
_renameHandler = (oldFullPath) => ProjectCollection.OnAfterRenameLoadedProject(oldFullPath, Owner);

Xml.OnAfterProjectRename += _renameHandler;
Xml.OnProjectXmlChanged += ProjectRootElement_ProjectXmlChangedHandler;
Expand Down
6 changes: 0 additions & 6 deletions src/Build/Definition/ToolsetReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ namespace Microsoft.Build.Evaluation
/// </summary>
internal abstract class ToolsetReader
{
/// <summary>
/// The global properties used to read the toolset.
/// </summary>
private PropertyDictionary<ProjectPropertyInstance> _globalProperties;

/// <summary>
/// The environment properties used to read the toolset.
/// </summary>
Expand All @@ -45,7 +40,6 @@ protected ToolsetReader(
PropertyDictionary<ProjectPropertyInstance> globalProperties)
{
_environmentProperties = environmentProperties;
_globalProperties = globalProperties;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ internal Builder(ImmutableList<ItemData>.Builder listBuilder)

#region IEnumerable implementation

private ImmutableList<ItemData>.Enumerator GetEnumerator() => _listBuilder.GetEnumerator();
IEnumerator<ItemData> IEnumerable<ItemData>.GetEnumerator() => _listBuilder.GetEnumerator();

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => _listBuilder.GetEnumerator();
Expand Down
2 changes: 2 additions & 0 deletions src/Build/Graph/GraphBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -662,8 +662,10 @@ public void AddOrUpdateEdge((ProjectGraphNode node, ProjectGraphNode reference)
{
ReferenceItems.AddOrUpdate(
key,
#pragma warning disable IDE0350
addValueFactory: static ((ProjectGraphNode node, ProjectGraphNode reference) key, ProjectItemInstance referenceItem) => referenceItem,
updateValueFactory: static ((ProjectGraphNode node, ProjectGraphNode reference) key, ProjectItemInstance existingItem, ProjectItemInstance newItem) =>
#pragma warning restore IDE0350
{
string existingTargetsMetadata = existingItem.GetMetadataValue(ItemMetadataNames.ProjectReferenceTargetsMetadataName);
string newTargetsMetadata = newItem.GetMetadataValue(ItemMetadataNames.ProjectReferenceTargetsMetadataName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,13 +175,11 @@ public ICollection<T> GetItems(string itemType)

private sealed class ListConverter : ICollection<T>
{
private readonly string _itemType;
private readonly ICollection<TCached> _list;
private readonly Func<TCached, T?> _getInstance;

public ListConverter(string itemType, ICollection<TCached> list, Func<TCached, T?> getInstance)
{
_itemType = itemType;
_list = list;
_getInstance = getInstance;
}
Expand Down
2 changes: 2 additions & 0 deletions src/Build/Instance/ProjectItemInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1085,6 +1085,7 @@ public void ImportMetadata(IEnumerable<KeyValuePair<string, string>> metadata)
_directMetadata.ImportProperties(metadata.Select(kvp => new ProjectMetadataInstance(kvp.Key, kvp.Value, allowItemSpecModifiers: true)));
}

#if FEATURE_APPDOMAIN
/// <summary>
/// Used to return metadata from another AppDomain. Can't use yield return because the
/// generated state machine is not marked as [Serializable], so we need to allocate.
Expand All @@ -1106,6 +1107,7 @@ private IEnumerable<KeyValuePair<string, string>> EnumerateMetadataEager(ICopyOn
// Probably better to send the raw array across the wire even if it's another allocation.
return result.ToArray();
}
#endif

private IEnumerable<KeyValuePair<string, string>> EnumerateMetadata(ICopyOnWritePropertyDictionary<ProjectMetadataInstance> list)
{
Expand Down
16 changes: 0 additions & 16 deletions src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1401,22 +1401,6 @@ private void WriteMessageAligned(string message, bool prefixAlreadyWritten, int
}
}

/// <summary>
/// Write message taking into account whether or not the prefix (timestamp and key) have already been written on the line
/// </summary>
private void WriteBasedOnPrefix(string nonNullMessage, bool prefixAlreadyWritten, int adjustedPrefixWidth)
{
if (prefixAlreadyWritten)
{
WriteHandler(nonNullMessage + Environment.NewLine);
}
else
{
// No prefix info has been written, indent the line to the proper location
WriteHandler(IndentString(nonNullMessage, adjustedPrefixWidth));
}
}

/// <summary>
/// Will display the target started event which was deferred until the first visible message for the target is ready to be displayed
/// </summary>
Expand Down
23 changes: 0 additions & 23 deletions src/MSBuild/MSBuildClientApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,28 +97,5 @@ public static MSBuildApp.ExitType Execute(

return MSBuildApp.ExitType.MSBuildClientFailure;
}

// Copied from NodeProviderOutOfProcBase.cs
#if RUNTIME_TYPE_NETCORE
private static string? CurrentHost;
private static string GetCurrentHost()
{
if (CurrentHost == null)
{
string dotnetExe = Path.Combine(FileUtilities.GetFolderAbove(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, 2),
NativeMethodsShared.IsWindows ? "dotnet.exe" : "dotnet");
if (File.Exists(dotnetExe))
{
CurrentHost = dotnetExe;
}
else
{
CurrentHost = EnvironmentUtilities.ProcessPath ?? throw new InvalidOperationException("Failed to retrieve process executable.");
}
}

return CurrentHost;
}
#endif
}
}
2 changes: 2 additions & 0 deletions src/MSBuild/XMake.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4526,6 +4526,7 @@ private static void ReplayBinaryLog(
}
}

#if FEATURE_XML_SCHEMA_VALIDATION
/// <summary>
/// Figures out if the project needs to be validated against a schema.
/// </summary>
Expand All @@ -4546,6 +4547,7 @@ private static string ProcessValidateSwitch(string[] parameters)

return schemaFile;
}
#endif

/// <summary>
/// Given an invalid ToolsVersion string and the collection of valid toolsets,
Expand Down
4 changes: 2 additions & 2 deletions src/Shared/AssemblyNameExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -989,8 +989,8 @@ public void Translate(ITranslator translator)

// TODO: consider some kind of protection against infinite loop during serialization, hint: pre serialize check for cycle in graph
translator.TranslateHashSet(ref remappedFrom,
(ITranslator t) => new AssemblyNameExtension(t),
(int capacity) => CreateRemappedFrom());
(t) => new AssemblyNameExtension(t),
(capacity) => CreateRemappedFrom());
}
}
}
Loading