Skip to content
Closed
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
1 change: 1 addition & 0 deletions eng/Analyzers.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<PackageReference Include="Microsoft.DotNet.CodeAnalysis" Version="$(MicrosoftDotNetCodeAnalysisVersion)" PrivateAssets="all" IsImplicitlyDefined="true" />
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersVersion)" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeStyle" Version="$(MicrosoftCodeAnalysisCSharpCodeStyleVersion)" PrivateAssets="all" />
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="16.8.55" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="$(StyleCopAnalyzersVersion)" PrivateAssets="all" />
</ItemGroup>
</Project>
10 changes: 10 additions & 0 deletions eng/CodeAnalysis.ruleset
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
<RuleSet Name="Microsoft.Analyzers.ManagedCodeAnalysis" Description="Microsoft.Analyzers.ManagedCodeAnalysis" ToolsVersion="14.0">
<Rules AnalyzerId="Microsoft.VisualStudio.Threading.Analyzers" RuleNamespace="Microsoft.VisualStudio.Threading.Analyzers">
<Rule Id="VSTHRD200" Action="None" />
<Rule Id="VSTHRD003" Action="None" />
<Rule Id="VSTHRD001" Action="None" />
<Rule Id="VSTHRD002" Action="None" />
<Rule Id="VSTHRD110" Action="None" />
<Rule Id="VSTHRD114" Action="None" />
<Rule Id="VSTHRD100" Action="None" />
<Rule Id="VSTHRD103" Action="Warning" />
</Rules>
<Rules AnalyzerId="Microsoft.DotNet.CodeAnalysis" RuleNamespace="Microsoft.DotNet.CodeAnalysis.Analyzers">
<Rule Id="BCL0001" Action="Warning" /> <!-- Ensure minimum API surface is respected -->
<Rule Id="BCL0010" Action="Warning" /> <!-- AppContext default value expected to be true -->
Expand Down
10 changes: 5 additions & 5 deletions src/libraries/System.IO.FileSystem/src/System/IO/File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ private static async Task<string> InternalReadAllTextAsync(string path, Encoding

if (string.IsNullOrEmpty(contents))
{
new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose();
new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose(); // await DisposeAsync
return Task.CompletedTask;
}

Expand Down Expand Up @@ -795,7 +795,7 @@ private static async Task<string> InternalReadAllTextAsync(string path, Encoding
{
if (!returningInternalTask)
{
fs.Dispose();
fs.Dispose(); // await DisposeAsync
}
}
}
Expand Down Expand Up @@ -862,7 +862,7 @@ private static async Task<byte[]> InternalReadAllBytesUnknownLengthAsync(FileStr
}
finally
{
fs.Dispose();
fs.Dispose(); // await DisposeAsync
ArrayPool<byte>.Shared.Return(rentedArray);
}
}
Expand Down Expand Up @@ -996,7 +996,7 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont
}
finally
{
sw.Dispose();
sw.Dispose(); // await DisposeAsync

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't understand what these comments are trying to say.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, I may have figured it out: What the suggested change is that would make the analyzer happier.

So I guess then my comment is "why are they comments instead of code changes?"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What the suggested change is that would make the analyzer happier.

The analyzer warning is noise in most if not all of its comments. We should not be making these changes (or at least none of the ones I've audited thus far).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@bartonjs you figured it out, yes.
My intention with this PR is to show what suggestions this analyzer would give us in runtime, and depending on how noisy it is (meaning how many would be false positives), decide what severity to approve for the API Proposal.
Which brings me back to the question:

  • Do we need to go through API proposal again or can this be approved offline?
  • Based on this level of noise, would it make sense to turn it on in runtime or should we disable it?
  • Since it's being noisy, should the severity be info for the rest of the world, or can it be added to roslyn-analyzers as warning?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Are they all were false positive? No any valid warnings? Is there any case we could tweak the analyzer to not warn for false positives?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need to go through API proposal again or can this be approved offline?

We don't need to go through API review.

Based on this level of noise, would it make sense to turn it on in runtime or should we disable it?

We should disable it.

Since it's being noisy, should the severity be info for the rest of the world, or can it be added to roslyn-analyzers as warning?

It should not be a warning. The noise we have with this in runtime is due to some common patterns that others use as well, e.g. a single method that has paths for sync and async, use of APIs that have an async alternative but where the developer knows the sync path is sufficient (e.g. FileStream.Dispose for a read-only FileStream), use of Task synchronous waiting methods on tasks known to already be complete, etc.

No any valid warnings?

It's possible there's a handful, but I doubt more than one or two that are legit, if that.

Is there any case we could tweak the analyzer to not warn for false positives?

It's possible, but it would need to be imbued with much more smarts.

We should definitely consider splitting functionality into multiple pieces. For example, I don't believe the warnings that fire for Task.Result/Wait/etc. should be part of this same diagnostic ID.

@carlossanlop carlossanlop Feb 23, 2021 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, @stephentoub !

We don't need to go through API review.

@terrajobst can you please do the honors and mark the proposal as api-approved? (If there are no more concerns, of course).

We should disable it.

So I'll just close this PR. No changes for runtime.

It should not be a warning.

I assume this means using the "Info" severity for the rest of the world. Is this correct?

We should definitely consider splitting functionality into multiple pieces.

No problem, I can start working on that when moving it to roslyn-analyzers.

if (buffer != null)
{
ArrayPool<char>.Shared.Return(buffer);
Expand Down Expand Up @@ -1024,7 +1024,7 @@ private static async Task InternalWriteAllTextAsync(StreamWriter sw, string cont
if (string.IsNullOrEmpty(contents))
{
// Just to throw exception if there is a problem opening the file.
new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose();
new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose(); // await DisposeAsync
return Task.CompletedTask;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ private Task<int> LastSyncCompletedReadTask(int val)
Task<int>? t = _lastSyncCompletedReadTask;
Debug.Assert(t == null || t.IsCompletedSuccessfully);

if (t != null && t.Result == val)
if (t != null && t.Result == val) // await t
return t;

t = Task.FromResult<int>(val);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ private unsafe void WriteCore(ReadOnlySpan<byte> source)
if (destination.Length < _bufferLength)
{
Task<int> readTask = ReadNativeAsync(new Memory<byte>(GetBuffer()), 0, cancellationToken);
_readLength = readTask.GetAwaiter().GetResult();
_readLength = readTask.GetAwaiter().GetResult(); // await readTask
int n = Math.Min(_readLength, destination.Length);
new Span<byte>(GetBuffer(), 0, n).CopyTo(destination.Span);
_readPos = n;
Expand Down Expand Up @@ -1452,7 +1452,7 @@ private async Task AsyncModeCopyToAsync(Stream destination, int bufferSize, Canc
finally
{
// Cleanup from the whole copy operation
cancellationReg.Dispose();
cancellationReg.Dispose(); // await DisposeAsync
awaitableOverlapped.Dispose();

ArrayPool<byte>.Shared.Return(copyBuffer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ private Task<int> ReadAsyncTask(byte[] buffer, int offset, int count, Cancellati
t = _lastSynchronouslyCompletedTask;
Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully");

if (t == null || t.Result != synchronousResult)
if (t == null || t.Result != synchronousResult) // await t
{
_lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Cancel
Task<int>? t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); // await t
}
catch (OperationCanceledException oce)
{
Expand Down Expand Up @@ -516,7 +516,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio
try
{
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
memStrDest.Write(_buffer, pos, n); // await WriteAsync
return Task.CompletedTask;
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Cancel
{
int n = Read(buffer, offset, count);
Task<int>? t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); // await t
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ internal static class TaskWhenAnyCast
// public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks);
// public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks);
// Used to "cast" from Task<Task> to Task<Task<TResult>>.
internal static readonly Func<Task<Task>, Task<TResult>> Value = completed => (Task<TResult>)completed.Result;
internal static readonly Func<Task<Task>, Task<TResult>> Value = completed => (Task<TResult>)completed.Result; // await completed
}

// Construct a promise-style task without any options.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static Task Unwrap(this Task<Task> task)
// task is null, return a canceled task to match the same semantics as CreateUnwrapPromise.
return
!task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise<VoidTaskResult>(task, lookForOce: false) :
task.Result ??
task.Result ?? // await task
Task.FromCanceled(new CancellationToken(true));
}

Expand All @@ -40,7 +40,7 @@ public static Task<TResult> Unwrap<TResult>(this Task<Task<TResult>> task)
// task is null, return a canceled task to match the same semantics as CreateUnwrapPromise.
return
!task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise<TResult>(task, lookForOce: false) :
task.Result ??
task.Result ?? // await task
Task.FromCanceled<TResult>(new CancellationToken(true));
}
}
Expand Down