Browse Source

Added missing ConfigureAwaits

release/3.x.x
Christian Kratky 7 years ago
parent
commit
7dfc19e588
9 changed files with 46 additions and 33 deletions
  1. +1
    -1
      MQTTnet.Core/Adapter/MqttChannelCommunicationAdapter.cs
  2. +2
    -2
      MQTTnet.Core/Client/MqttClient.cs
  3. +6
    -2
      MQTTnet.Core/Diagnostics/MqttNetLogger.cs
  4. +4
    -2
      MQTTnet.Core/Diagnostics/MqttNetTrace.cs
  5. +10
    -7
      MQTTnet.Core/Serializer/MqttPacketSerializer.cs
  6. +3
    -3
      MQTTnet.Core/Serializer/MqttPacketWriter.cs
  7. +2
    -2
      MQTTnet.Core/Server/MqttClientRetainedMessagesManager.cs
  8. +10
    -10
      MQTTnet.Core/Server/MqttClientSession.cs
  9. +8
    -4
      Tests/MQTTnet.TestApp.NetCore/PerformanceTest.cs

+ 1
- 1
MQTTnet.Core/Adapter/MqttChannelCommunicationAdapter.cs View File

@@ -87,7 +87,7 @@ namespace MQTTnet.Core.Adapter
{ {
try try
{ {
await _semaphore.WaitAsync(cancellationToken);
await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);


foreach (var packet in packets) foreach (var packet in packets)
{ {


+ 2
- 2
MQTTnet.Core/Client/MqttClient.cs View File

@@ -151,7 +151,7 @@ namespace MQTTnet.Core.Client
case MqttQualityOfServiceLevel.AtMostOnce: case MqttQualityOfServiceLevel.AtMostOnce:
{ {
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier] // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, qosPackets);
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, qosPackets).ConfigureAwait(false);
break; break;
} }
case MqttQualityOfServiceLevel.AtLeastOnce: case MqttQualityOfServiceLevel.AtLeastOnce:
@@ -159,7 +159,7 @@ namespace MQTTnet.Core.Client
foreach (var publishPacket in qosPackets) foreach (var publishPacket in qosPackets)
{ {
publishPacket.PacketIdentifier = GetNewPacketIdentifier(); publishPacket.PacketIdentifier = GetNewPacketIdentifier();
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket).ConfigureAwait(false);
} }


break; break;


+ 6
- 2
MQTTnet.Core/Diagnostics/MqttNetLogger.cs View File

@@ -21,15 +21,19 @@ namespace MQTTnet.Core.Diagnostics
throw new ArgumentNullException(nameof(formatter)); throw new ArgumentNullException(nameof(formatter));
} }


var message = formatter(state, exception);
if (!MqttNetTrace.HasListeners)
{
return;
}


var message = formatter(state, exception);
var traceMessage = new MqttNetTraceMessage(DateTime.Now, Environment.CurrentManagedThreadId, _categoryName, logLevel, message, exception); var traceMessage = new MqttNetTraceMessage(DateTime.Now, Environment.CurrentManagedThreadId, _categoryName, logLevel, message, exception);
_mqttNetTrace.Publish(traceMessage); _mqttNetTrace.Publish(traceMessage);
} }


public bool IsEnabled(LogLevel logLevel) public bool IsEnabled(LogLevel logLevel)
{ {
return true;
return MqttNetTrace.HasListeners;
} }


//not supported: async local requires netstandard1.3 //not supported: async local requires netstandard1.3


+ 4
- 2
MQTTnet.Core/Diagnostics/MqttNetTrace.cs View File

@@ -10,9 +10,11 @@ namespace MQTTnet.Core.Diagnostics


public static event EventHandler<MqttNetTraceMessagePublishedEventArgs> TraceMessagePublished; public static event EventHandler<MqttNetTraceMessagePublishedEventArgs> TraceMessagePublished;


public void Publish(MqttNetTraceMessage msg)
public static bool HasListeners => TraceMessagePublished != null;

public void Publish(MqttNetTraceMessage traceMessage)
{ {
TraceMessagePublished?.Invoke(this, new MqttNetTraceMessagePublishedEventArgs(msg));
TraceMessagePublished?.Invoke(this, new MqttNetTraceMessagePublishedEventArgs(traceMessage));
} }


public void Dispose() public void Dispose()


+ 10
- 7
MQTTnet.Core/Serializer/MqttPacketSerializer.cs View File

@@ -24,15 +24,18 @@ namespace MQTTnet.Core.Serializer
using (var stream = new MemoryStream()) using (var stream = new MemoryStream())
using (var writer = new MqttPacketWriter(stream)) using (var writer = new MqttPacketWriter(stream))
{ {
var header = new List<byte> { SerializePacket(packet, writer) };
var fixedHeader = SerializePacket(packet, writer);
var headerBuffer = new List<byte> { fixedHeader };
MqttPacketWriter.WriteRemainingLength((int)stream.Length, headerBuffer);

var header = headerBuffer.ToArray();
var body = stream.ToArray(); var body = stream.ToArray();
MqttPacketWriter.BuildLengthHeader(body.Length, header);
var headerArray = header.ToArray();
var writeBuffer = new byte[header.Count + body.Length];
Buffer.BlockCopy(headerArray, 0, writeBuffer, 0, headerArray.Length);
Buffer.BlockCopy(body, 0, writeBuffer, headerArray.Length, body.Length);


return writeBuffer;
var buffer = new byte[header.Length + body.Length];
Buffer.BlockCopy(header, 0, buffer, 0, header.Length);
Buffer.BlockCopy(body, 0, buffer, header.Length, body.Length);

return buffer;
} }
} }




+ 3
- 3
MQTTnet.Core/Serializer/MqttPacketWriter.cs View File

@@ -56,11 +56,11 @@ namespace MQTTnet.Core.Serializer
Write(value); Write(value);
} }


public static void BuildLengthHeader(int length, List<byte> header)
public static void WriteRemainingLength(int length, List<byte> target)
{ {
if (length == 0) if (length == 0)
{ {
header.Add(0);
target.Add(0);
return; return;
} }


@@ -75,7 +75,7 @@ namespace MQTTnet.Core.Serializer
encodedByte = encodedByte | 128; encodedByte = encodedByte | 128;
} }


header.Add((byte)encodedByte);
target.Add((byte)encodedByte);
} while (x > 0); } while (x > 0);
} }
} }


+ 2
- 2
MQTTnet.Core/Server/MqttClientRetainedMessagesManager.cs View File

@@ -54,7 +54,7 @@ namespace MQTTnet.Core.Server
{ {
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage)); if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));


await _gate.WaitAsync();
await _gate.WaitAsync().ConfigureAwait(false);
try try
{ {
var saveIsRequired = false; var saveIsRequired = false;
@@ -108,7 +108,7 @@ namespace MQTTnet.Core.Server
{ {
var retainedMessages = new List<MqttApplicationMessage>(); var retainedMessages = new List<MqttApplicationMessage>();


await _gate.WaitAsync();
await _gate.WaitAsync().ConfigureAwait(false);
try try
{ {
foreach (var retainedMessage in _retainedMessages.Values) foreach (var retainedMessage in _retainedMessages.Values)


+ 10
- 10
MQTTnet.Core/Server/MqttClientSession.cs View File

@@ -29,11 +29,11 @@ namespace MQTTnet.Core.Server
private MqttApplicationMessage _willMessage; private MqttApplicationMessage _willMessage;


public MqttClientSession( public MqttClientSession(
string clientId,
string clientId,
IOptions<MqttServerOptions> options, IOptions<MqttServerOptions> options,
MqttClientSessionsManager sessionsManager, MqttClientSessionsManager sessionsManager,
MqttClientSubscriptionsManager subscriptionsManager, MqttClientSubscriptionsManager subscriptionsManager,
ILogger<MqttClientSession> logger,
ILogger<MqttClientSession> logger,
ILogger<MqttClientPendingMessagesQueue> messageQueueLogger, ILogger<MqttClientPendingMessagesQueue> messageQueueLogger,
IMqttClientRetainedMessageManager clientRetainedMessageManager) IMqttClientRetainedMessageManager clientRetainedMessageManager)
{ {
@@ -65,7 +65,7 @@ namespace MQTTnet.Core.Server
_cancellationTokenSource = new CancellationTokenSource(); _cancellationTokenSource = new CancellationTokenSource();


_pendingMessagesQueue.Start(adapter, _cancellationTokenSource.Token); _pendingMessagesQueue.Start(adapter, _cancellationTokenSource.Token);
await ReceivePacketsAsync(adapter, _cancellationTokenSource.Token);
await ReceivePacketsAsync(adapter, _cancellationTokenSource.Token).ConfigureAwait(false);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
@@ -175,7 +175,7 @@ namespace MQTTnet.Core.Server
{ {
return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, _subscriptionsManager.Unsubscribe(unsubscribePacket)); return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, _subscriptionsManager.Unsubscribe(unsubscribePacket));
} }
if (packet is MqttDisconnectPacket || packet is MqttConnectPacket) if (packet is MqttDisconnectPacket || packet is MqttConnectPacket)
{ {
Stop(); Stop();
@@ -192,19 +192,19 @@ namespace MQTTnet.Core.Server
{ {
var subscribeResult = _subscriptionsManager.Subscribe(subscribePacket, ClientId); var subscribeResult = _subscriptionsManager.Subscribe(subscribePacket, ClientId);


await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, subscribeResult.ResponsePacket);
await EnqueueSubscribedRetainedMessagesAsync(subscribePacket);
await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, subscribeResult.ResponsePacket).ConfigureAwait(false);
await EnqueueSubscribedRetainedMessagesAsync(subscribePacket).ConfigureAwait(false);


if (subscribeResult.CloseConnection) if (subscribeResult.CloseConnection)
{ {
await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttDisconnectPacket());
await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttDisconnectPacket()).ConfigureAwait(false);
Stop(); Stop();
} }
} }


private async Task EnqueueSubscribedRetainedMessagesAsync(MqttSubscribePacket subscribePacket) private async Task EnqueueSubscribedRetainedMessagesAsync(MqttSubscribePacket subscribePacket)
{ {
var retainedMessages = await _clientRetainedMessageManager.GetSubscribedMessagesAsync(subscribePacket);
var retainedMessages = await _clientRetainedMessageManager.GetSubscribedMessagesAsync(subscribePacket).ConfigureAwait(false);
foreach (var publishPacket in retainedMessages) foreach (var publishPacket in retainedMessages)
{ {
EnqueuePublishPacket(publishPacket.ToPublishPacket()); EnqueuePublishPacket(publishPacket.ToPublishPacket());
@@ -225,7 +225,7 @@ namespace MQTTnet.Core.Server


if (applicationMessage.Retain) if (applicationMessage.Retain)
{ {
await _clientRetainedMessageManager.HandleMessageAsync(ClientId, applicationMessage);
await _clientRetainedMessageManager.HandleMessageAsync(ClientId, applicationMessage).ConfigureAwait(false);
} }


switch (applicationMessage.QualityOfServiceLevel) switch (applicationMessage.QualityOfServiceLevel)
@@ -255,7 +255,7 @@ namespace MQTTnet.Core.Server
_sessionsManager.DispatchApplicationMessage(this, applicationMessage); _sessionsManager.DispatchApplicationMessage(this, applicationMessage);


await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken,
new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier }).ConfigureAwait(false);


return; return;
} }


+ 8
- 4
Tests/MQTTnet.TestApp.NetCore/PerformanceTest.cs View File

@@ -41,7 +41,7 @@ namespace MQTTnet.TestApp.NetCore
.AddLogging() .AddLogging()
.BuildServiceProvider(); .BuildServiceProvider();


services.GetService<ILoggerFactory>().AddConsole(LogLevel.Warning, true);
//services.GetService<ILoggerFactory>().AddConsole(LogLevel.Warning, true);


Console.WriteLine("Press 'c' for concurrent sends. Otherwise in one batch."); Console.WriteLine("Press 'c' for concurrent sends. Otherwise in one batch.");
var concurrent = Console.ReadKey(true).KeyChar == 'c'; var concurrent = Console.ReadKey(true).KeyChar == 'c';
@@ -120,11 +120,15 @@ namespace MQTTnet.TestApp.NetCore
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message)."); Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message).");


stopwatch.Restart();

var messages = new[] { message };
var sentMessagesCount = 0; var sentMessagesCount = 0;

stopwatch.Restart();

while (stopwatch.ElapsedMilliseconds < 1000) while (stopwatch.ElapsedMilliseconds < 1000)
{ {
await client.PublishAsync(message);
await client.PublishAsync(messages).ConfigureAwait(false);
sentMessagesCount++; sentMessagesCount++;
} }


@@ -180,7 +184,7 @@ namespace MQTTnet.TestApp.NetCore
{ {
Topic = "A/B/C", Topic = "A/B/C",
Payload = Encoding.UTF8.GetBytes("Hello World"), Payload = Encoding.UTF8.GetBytes("Hello World"),
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
}; };
} }




Loading…
Cancel
Save