Skip to content

Commit 4b20f30

Browse files
authored
Fix CA2008;CA2012;CA2016;CA1835;CA2208; (#2139)
* Fix CA2008;CA2012;CA2016;CA1835;CA2208; * Resolve comments and fix tests
1 parent 7326cbc commit 4b20f30

24 files changed

Lines changed: 122 additions & 105 deletions

File tree

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
<ThirdPartyAssemblySigningCertName>3PartySHA2</ThirdPartyAssemblySigningCertName>
3030
<PackageSigningCertName>NuGet</PackageSigningCertName>
3131
<!-- Disable the warnings for now, enable batch by batch later-->
32-
<NoWarn>$(NoWarn);CA2007;CA2008;CA2012;CA2016;CA1835;CA2208;IDE0161;IDE0130;IDE0290;IDE1006;IDE0090</NoWarn>
32+
<NoWarn>$(NoWarn);CA2007;IDE0161;IDE0130;IDE0290;IDE1006;IDE0090</NoWarn>
3333
</PropertyGroup>
3434

3535
<ItemGroup>

samples/AspNet.ChatSample/AspNet.ChatSample.CSharpClient/Program.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ sealed class Program
1717
static async Task Main(string[] args)
1818
{
1919
var url = "http://localhost:8009";
20-
var proxy = await ConnectAsync(url, Console.Out);
20+
var proxy = await ConnectAsync(url, Console.Out).ConfigureAwait(false);
2121
var currentUser = Guid.NewGuid().ToString("N");
2222

2323
Mode mode = Mode.Broadcast;
@@ -33,11 +33,11 @@ static async Task Main(string[] args)
3333
switch (mode)
3434
{
3535
case Mode.Broadcast:
36-
await proxy.Invoke("BroadcastMessage", currentUser, input);
36+
await proxy.Invoke("BroadcastMessage", currentUser, input).ConfigureAwait(false);
3737

3838
break;
3939
case Mode.Echo:
40-
await proxy.Invoke("echo", input);
40+
await proxy.Invoke("echo", input).ConfigureAwait(false);
4141
break;
4242
default:
4343
break;
@@ -71,15 +71,15 @@ private static async Task<IHubProxy> ConnectAsync(string url, TextWriter output,
7171
hubProxy.On<string, string>("BroadcastMessage", BroadcastMessage);
7272
hubProxy.On<string>("Echo", Echo);
7373

74-
await StartAsyncWithAlwaysRetry(connection, output, cancellationToken: cancellationToken);
74+
await StartAsyncWithAlwaysRetry(connection, output, cancellationToken: cancellationToken).ConfigureAwait(false);
7575

7676
return hubProxy;
7777
}
7878

7979
private static async Task StartAsyncWithAlwaysRetry(HubConnection connection, TextWriter output, Task startDelay = null, CancellationToken cancellationToken = default)
8080
{
8181
// When there is already a reconnect, directly return;
82-
if (!ReconnectLock.Wait(0))
82+
if (!ReconnectLock.Wait(0, CancellationToken.None))
8383
{
8484
return;
8585
}
@@ -88,21 +88,21 @@ private static async Task StartAsyncWithAlwaysRetry(HubConnection connection, Te
8888
{
8989
if (startDelay != null)
9090
{
91-
await startDelay;
91+
await startDelay.ConfigureAwait(false);
9292
}
9393

9494
while (!cancellationToken.IsCancellationRequested)
9595
{
9696
try
9797
{
9898
// Sometimes Start throws and triggers Error event, however sometimes not.
99-
await connection.Start();
99+
await connection.Start().ConfigureAwait(false);
100100
return;
101101
}
102102
catch (Exception e)
103103
{
104104
output.WriteLine($"Error starting: {e.Message}, retry...");
105-
await ReconnectDelayTask();
105+
await ReconnectDelayTask().ConfigureAwait(false);
106106
}
107107
}
108108
}

samples/ChatSample/ChatSample.CSharpClient/Program.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ sealed class Program
1616
static async Task Main(string[] args)
1717
{
1818
var url = "http://localhost:5050";
19-
var proxy = await ConnectAsync(url + "/chat", Console.Out);
19+
var proxy = await ConnectAsync(url + "/chat", Console.Out).ConfigureAwait(false);
2020
var currentUser = Guid.NewGuid().ToString("N");
2121

2222
Mode mode = Mode.Broadcast;
@@ -32,10 +32,10 @@ static async Task Main(string[] args)
3232
switch (mode)
3333
{
3434
case Mode.Broadcast:
35-
await proxy.InvokeAsync("BroadcastMessage", currentUser, input);
35+
await proxy.InvokeAsync("BroadcastMessage", currentUser, input).ConfigureAwait(false);
3636
break;
3737
case Mode.Echo:
38-
await proxy.InvokeAsync("echo", input);
38+
await proxy.InvokeAsync("echo", input).ConfigureAwait(false);
3939
break;
4040
default:
4141
break;
@@ -55,7 +55,7 @@ private static async Task<HubConnection> ConnectAsync(string url, TextWriter out
5555
connection.On<string, string>("BroadcastMessage", BroadcastMessage);
5656
connection.On<string>("Echo", Echo);
5757

58-
await StartAsyncWithRetry(connection, output, cancellationToken);
58+
await StartAsyncWithRetry(connection, output, cancellationToken).ConfigureAwait(false);
5959

6060
return connection;
6161
}
@@ -66,13 +66,13 @@ private static async Task StartAsyncWithRetry(HubConnection connection, TextWrit
6666
{
6767
try
6868
{
69-
await connection.StartAsync(cancellationToken);
69+
await connection.StartAsync(cancellationToken).ConfigureAwait(false);
7070
return;
7171
}
7272
catch (Exception e)
7373
{
7474
output.WriteLine($"Error starting: {e.Message}, retry...");
75-
await Task.Delay(GetRandomDelayMilliseconds());
75+
await Task.Delay(GetRandomDelayMilliseconds(), cancellationToken).ConfigureAwait(false);
7676
}
7777
}
7878
}

samples/ChatSample/ChatSample.ManagementPublisher/MessagePublisher.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public Task SendMessages(string command, string? receiver, string message)
3030
{
3131
if (_hubContext == null)
3232
{
33-
throw new ArgumentNullException(nameof(_hubContext));
33+
throw new ArgumentException("Call InitAsync to create HubContext first.");
3434
}
3535
switch (command)
3636
{
@@ -52,7 +52,7 @@ public Task CloseConnection(string connectionId, string reason)
5252
{
5353
if (_hubContext == null)
5454
{
55-
throw new ArgumentNullException(nameof(_hubContext));
55+
throw new ArgumentException("Call InitAsync to create HubContext first.");
5656
}
5757
return _hubContext.ClientManager.CloseConnectionAsync(connectionId, reason);
5858
}
@@ -61,7 +61,7 @@ public Task<bool> CheckExist(string type, string id)
6161
{
6262
if (_hubContext == null)
6363
{
64-
throw new ArgumentNullException(nameof(_hubContext));
64+
throw new ArgumentException("Call InitAsync to create HubContext first.");
6565
}
6666
return type switch
6767
{

samples/ChatSample/ChatSample.Net60/StreamingService.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
// Copyright (c) Microsoft. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4-
54
using ChatSample.Net60.Hubs;
65
using Microsoft.AspNetCore.SignalR;
7-
using Microsoft.Extensions.Logging;
86

97
namespace ChatSample.Net60
108
{
@@ -17,9 +15,10 @@ public StreamingService(IHubContext<ChatHub> hubContext, ILogger<StreamingServic
1715
_hubContext = hubContext;
1816
_logger = logger;
1917
}
18+
2019
public Task StartAsync(CancellationToken cancellationToken)
2120
{
22-
return Task.Factory.StartNew(() => StreamingTask(cancellationToken), TaskCreationOptions.LongRunning);
21+
return Task.Factory.StartNew(() => StreamingTask(cancellationToken), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
2322
}
2423

2524
public Task StopAsync(CancellationToken cancellationToken)
@@ -33,17 +32,17 @@ private async Task StreamingTask(CancellationToken cancellationToken)
3332

3433
_logger.LogInformation("Waiting");
3534

36-
await Task.Delay(5000);
35+
await Task.Delay(5000, cancellationToken);
3736

3837
_logger.LogInformation("Spamming");
3938

4039
while (!cancellationToken.IsCancellationRequested)
4140
{
4241
counter++;
4342

44-
await _hubContext.Clients.All.SendAsync("ReceiveMessage", counter, counter);
43+
await _hubContext.Clients.All.SendAsync("ReceiveMessage", counter, counter, cancellationToken);
4544

46-
await Task.Delay(1);
45+
await Task.Delay(1, cancellationToken);
4746
}
4847
}
4948
}

src/Common/MemoryBufferWriter.cs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,10 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio
138138
if (_completedSegments == null)
139139
{
140140
// There is only one segment so write without awaiting.
141-
return destination.WriteAsync(_currentSegment!, 0, _position);
141+
return destination.WriteAsync(_currentSegment!, 0, _position, cancellationToken);
142142
}
143143

144-
return CopyToSlowAsync(destination);
144+
return CopyToSlowAsync(destination, cancellationToken);
145145
}
146146

147147
private void EnsureCapacity(int sizeHint)
@@ -182,7 +182,7 @@ private void AddSegment(int sizeHint = 0)
182182
_position = 0;
183183
}
184184

185-
private async Task CopyToSlowAsync(Stream destination)
185+
private async Task CopyToSlowAsync(Stream destination, CancellationToken cancellationToken)
186186
{
187187
if (_completedSegments != null)
188188
{
@@ -191,11 +191,20 @@ private async Task CopyToSlowAsync(Stream destination)
191191
for (var i = 0; i < count; i++)
192192
{
193193
var segment = _completedSegments[i];
194-
await destination.WriteAsync(segment.Buffer, 0, segment.Length);
194+
#if NET6_0_OR_GREATER
195+
await destination.WriteAsync(segment.Buffer.AsMemory(0, segment.Length), cancellationToken);
196+
#else
197+
198+
await destination.WriteAsync(segment.Buffer, 0, segment.Length, cancellationToken);
199+
#endif
195200
}
196201
}
202+
#if NET6_0_OR_GREATER
203+
await destination.WriteAsync(_currentSegment!.AsMemory(0, _position), cancellationToken);
204+
#else
197205

198-
await destination.WriteAsync(_currentSegment!, 0, _position);
206+
await destination.WriteAsync(_currentSegment!, 0, _position, cancellationToken);
207+
#endif
199208
}
200209

201210
public byte[] ToArray()

src/Microsoft.Azure.SignalR.Common/ServiceConnections/Internal/ForceAsyncAwaiter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// Copyright (c) .NET Foundation. All rights reserved.
2-
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System.Runtime.CompilerServices;
55

src/Microsoft.Azure.SignalR.Common/ServiceConnections/MultiEndpointServiceConnectionContainer.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,6 @@ public Task<bool> WriteAckableMessageAsync(ServiceMessage serviceMessage, Cancel
155155
return CreateMessageWriter(serviceMessage).WriteAckableMessageAsync(serviceMessage, cancellationToken);
156156
}
157157

158-
159158
public IAsyncEnumerable<GroupMember> ListConnectionsInGroupAsync(string groupName, int? top = null, ulong? tracingId = null, CancellationToken token = default)
160159
{
161160
var targetEndpoints = _routerEndpoints.needRouter ? _router.GetEndpointsForGroup(groupName, _routerEndpoints.endpoints) : _routerEndpoints.endpoints;

src/Microsoft.Azure.SignalR.Common/ServiceConnections/ServiceConnectionBase.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,10 @@ protected virtual Task DispatchMessageAsync(ServiceMessage message)
367367
};
368368
}
369369

370+
/// <summary>
371+
/// Looks like it is virtual for ut, pretty tricky, TODO: improve, could use configurable keepaliveticks options to disable the ping
372+
/// </summary>
373+
/// <returns></returns>
370374
protected virtual async ValueTask TrySendPingAsync()
371375
{
372376
if (!_writeLock.Wait(0))
@@ -652,7 +656,7 @@ private async Task ProcessIncomingAsync(ConnectionContext connection)
652656
UpdateReceiveTimestamp();
653657

654658
// No matter what kind of message come in, trigger send ping check
655-
_ = TrySendPingAsync();
659+
await TrySendPingAsync();
656660

657661
while (ServiceProtocol.TryParseMessage(ref buffer, out var message))
658662
{

src/Microsoft.Azure.SignalR.Common/Utilities/AckHandler.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,17 +50,17 @@ public Task<AckStatus> CreateSingleAck(out int id, TimeSpan? ackTimeout = defaul
5050
return info.Task;
5151
}
5252

53-
public Task<T> CreateSingleAck<T>(out int id, TimeSpan? ackTimeout = default, CancellationToken cancellationToken = default) where T : notnull, new()
53+
public Task<T> CreateSingleAck<T>(out int id, TimeSpan? ackTimeout = default, CancellationToken cancellationToken = default) where T : notnull, new()
54+
{
55+
id = NextId();
56+
if (_disposed)
5457
{
55-
id = NextId();
56-
if (_disposed)
57-
{
58-
return Task.FromResult(new T());
59-
}
60-
var info = (SinglePayloadAck<T>)_acks.GetOrAdd(id, _ => new SinglePayloadAck<T>(ackTimeout ?? _defaultAckTimeout));
61-
cancellationToken.Register(info.Cancel);
62-
return info.Task.ContinueWith(task => task.Result);
58+
return Task.FromResult(new T());
6359
}
60+
var info = (SinglePayloadAck<T>)_acks.GetOrAdd(id, _ => new SinglePayloadAck<T>(ackTimeout ?? _defaultAckTimeout));
61+
cancellationToken.Register(info.Cancel);
62+
return info.Task.ContinueWith(task => task.Result, TaskScheduler.Default);
63+
}
6464

6565
public static bool HandleAckStatus(IAckableMessage message, AckStatus status)
6666
{

0 commit comments

Comments
 (0)