Skip to content

Commit

Permalink
为了提升性能,在同步调用异步时规避卡UI上下文,所有await状态机都设置ConfigureAwait(false),开启CA2007并视…
Browse files Browse the repository at this point in the history
…为编译错误。减少不必要的await状态机
  • Loading branch information
nnhy committed Dec 1, 2024
1 parent bc49433 commit bbc3494
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 44 deletions.
10 changes: 5 additions & 5 deletions NewLife.MQTT/AliyunMqttClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ public AliyunMqttClient(String productKey, String deviceName, String deviceSecre
/// <returns></returns>
public virtual async Task PostProperty(Object data)
{
await SubscribeAsync($"/sys/{ProductKey}/{DeviceName}/thing/event/property/post_reply", OnPostProperty);
await SubscribeAsync($"/sys/{ProductKey}/{DeviceName}/thing/event/property/post_reply", OnPostProperty).ConfigureAwait(false);
await PublishAsync($"/sys/{ProductKey}/{DeviceName}/thing/event/property/post", new
{
//id = 1,
@params = data,
method = "thing.event.property.post"
});
}).ConfigureAwait(false);

await SubscribeAsync($"/sys/{ProductKey}/{DeviceName}/thing/service/property/set", OnSetProperty);
await SubscribeAsync($"/sys/{ProductKey}/{DeviceName}/thing/service/property/set", OnSetProperty).ConfigureAwait(false);
}

/// <summary>收到属性上报</summary>
Expand All @@ -72,8 +72,8 @@ public virtual async Task PostProperty(Object data)
/// <returns></returns>
public async Task SyncTime()
{
await SubscribeAsync($"/ext/ntp/{ProductKey}/{DeviceName}/response", OnSyncTime);
await PublishAsync($"/ext/ntp/{ProductKey}/{DeviceName}/request", new { version = "1.0" });
await SubscribeAsync($"/ext/ntp/{ProductKey}/{DeviceName}/response", OnSyncTime).ConfigureAwait(false);
await PublishAsync($"/ext/ntp/{ProductKey}/{DeviceName}/request", new { version = "1.0" }).ConfigureAwait(false);
}

/// <summary>收到时间同步</summary>
Expand Down
30 changes: 15 additions & 15 deletions NewLife.MQTT/Clusters/ClusterNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,11 @@ private void Init()
/// <summary>回响</summary>
/// <param name="msg"></param>
/// <returns></returns>
public async Task<String?> Echo(String msg)
public Task<String?> Echo(String msg)
{
Init();

return await Client.InvokeAsync<String>("Cluster/Echo", msg).ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Echo", msg);
}

/// <summary>加入集群</summary>
Expand All @@ -95,61 +95,61 @@ private void Init()
}

/// <summary>心跳</summary>
public async Task<NodeInfo?> Ping(NodeInfo info)
public Task<NodeInfo?> Ping(NodeInfo info)
{
Init();

_myNode = info;

if (_remoteNode == null)
return await Join(info);
return Join(info);
else
return await Client.InvokeAsync<NodeInfo>("Cluster/Ping", info).ConfigureAwait(false);
return Client.InvokeAsync<NodeInfo>("Cluster/Ping", info);
}

/// <summary>离开集群</summary>
public async Task<String?> Leave(NodeInfo info)
public Task<String?> Leave(NodeInfo info)
{
Init();

return await Client.InvokeAsync<String>("Cluster/Leave", info).ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Leave", info);
}

/// <summary>订阅</summary>
/// <param name="infos"></param>
/// <returns></returns>
public async Task<String?> Subscribe(SubscriptionInfo[] infos)
public Task<String?> Subscribe(SubscriptionInfo[] infos)
{
Init();

return await Client.InvokeAsync<String>("Cluster/Subscribe", infos).ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Subscribe", infos);
}

/// <summary>退订</summary>
/// <param name="infos"></param>
/// <returns></returns>
public async Task<String?> Unsubscribe(SubscriptionInfo[] infos)
public Task<String?> Unsubscribe(SubscriptionInfo[] infos)
{
Init();

return await Client.InvokeAsync<String>("Cluster/Unsubscribe", infos).ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Unsubscribe", infos);
}

/// <summary>心跳</summary>
/// <returns></returns>
public async Task<String?> Ping()
public Task<String?> Ping()
{
Init();

return await Client.InvokeAsync<String>("Cluster/Ping").ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Ping");
}

/// <summary>发布</summary>
public async Task<String?> Publish(PublishInfo info)
public Task<String?> Publish(PublishInfo info)
{
Init();

return await Client.InvokeAsync<String>("Cluster/Publish", info).ConfigureAwait(false);
return Client.InvokeAsync<String>("Cluster/Publish", info);
}
#endregion
}
8 changes: 4 additions & 4 deletions NewLife.MQTT/Handlers/IMqttHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ protected virtual UnsubAck OnUnsubscribe(UnsubscribeMessage message)
/// <param name="data">消息数据</param>
/// <param name="qos">服务质量</param>
/// <returns></returns>
public async Task<MqttIdMessage?> PublishAsync(String topic, Object data, QualityOfService qos = QualityOfService.AtMostOnce)
public Task<MqttIdMessage?> PublishAsync(String topic, Object data, QualityOfService qos = QualityOfService.AtMostOnce)
{
var pk = data as IPacket;
if (pk == null && data != null) pk = Encoder.Encode(data);
Expand All @@ -202,7 +202,7 @@ protected virtual UnsubAck OnUnsubscribe(UnsubscribeMessage message)
QoS = qos,
};

return await PublishAsync(message);
return PublishAsync(message);
}

/// <summary>发布消息</summary>
Expand All @@ -211,7 +211,7 @@ protected virtual UnsubAck OnUnsubscribe(UnsubscribeMessage message)
/// <param name="qos">服务质量</param>
/// <param name="allowExchange">允许消息交换</param>
/// <returns></returns>
public async Task<MqttIdMessage?> PublishAsync(String topic, Object data, Boolean allowExchange, QualityOfService qos = QualityOfService.AtMostOnce)
public Task<MqttIdMessage?> PublishAsync(String topic, Object data, Boolean allowExchange, QualityOfService qos = QualityOfService.AtMostOnce)
{
var pk = data as IPacket;
if (pk == null && data != null) pk = Encoder.Encode(data);
Expand All @@ -231,7 +231,7 @@ protected virtual UnsubAck OnUnsubscribe(UnsubscribeMessage message)
ClusterExchange?.Publish(Session, message);
}

return await PublishAsync(message);
return PublishAsync(message);
}

/// <summary>发布消息</summary>
Expand Down
22 changes: 11 additions & 11 deletions NewLife.MQTT/MqttClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ private void Client_Received(Object sender, ReceivedEventArgs e)

/// <summary>连接服务端</summary>
/// <returns></returns>
public async Task<ConnAck> ConnectAsync()
public Task<ConnAck> ConnectAsync()
{
if (ClientId.IsNullOrEmpty()) throw new ArgumentNullException(nameof(ClientId));

Expand All @@ -370,7 +370,7 @@ public async Task<ConnAck> ConnectAsync()
CleanSession = CleanSession,
};

return await ConnectAsync(message);
return ConnectAsync(message);
}

/// <summary>连接服务端</summary>
Expand Down Expand Up @@ -458,7 +458,7 @@ private void Client_Closed(Object sender, EventArgs e)
/// <param name="data">消息数据</param>
/// <param name="qos">服务质量</param>
/// <returns></returns>
public async Task<MqttIdMessage?> PublishAsync(String topic, Object data, QualityOfService qos = QualityOfService.AtMostOnce)
public Task<MqttIdMessage?> PublishAsync(String topic, Object data, QualityOfService qos = QualityOfService.AtMostOnce)
{
var pk = data as IPacket;
if (pk == null && data != null) pk = Encoder.Encode(data);
Expand All @@ -471,7 +471,7 @@ private void Client_Closed(Object sender, EventArgs e)
QoS = qos,
};

return await PublishAsync(message);
return PublishAsync(message);
}

/// <summary>发布消息</summary>
Expand Down Expand Up @@ -499,22 +499,22 @@ private void Client_Closed(Object sender, EventArgs e)
/// <param name="topicFilter">主题过滤器</param>
/// <param name="callback">收到该主题消息时的回调</param>
/// <returns></returns>
public async Task<SubAck?> SubscribeAsync(String topicFilter, Action<PublishMessage>? callback = null)
public Task<SubAck?> SubscribeAsync(String topicFilter, Action<PublishMessage>? callback = null)
{
var subscription = new Subscription(topicFilter, QualityOfService.AtMostOnce);

return await SubscribeAsync([subscription], callback);
return SubscribeAsync([subscription], callback);
}

/// <summary>订阅主题</summary>
/// <param name="topicFilters">主题过滤器</param>
/// <param name="qos">服务质量</param>
/// <returns></returns>
public async Task<SubAck?> SubscribeAsync(String[] topicFilters, QualityOfService qos = QualityOfService.AtMostOnce)
public Task<SubAck?> SubscribeAsync(String[] topicFilters, QualityOfService qos = QualityOfService.AtMostOnce)
{
var subscriptions = topicFilters.Select(e => new Subscription(e, qos)).ToList();

return await SubscribeAsync(subscriptions);
return SubscribeAsync(subscriptions);
}

/// <summary>订阅主题</summary>
Expand All @@ -532,7 +532,7 @@ private void Client_Closed(Object sender, EventArgs e)
Requests = subscriptions,
};

var rs = (await SendAsync(message)) as SubAck;
var rs = (await SendAsync(message).ConfigureAwait(false)) as SubAck;
if (rs != null)
{
foreach (var item in subscriptions)
Expand All @@ -555,7 +555,7 @@ private void Client_Closed(Object sender, EventArgs e)
TopicFilters = topicFilters,
};

var rs = (await SendAsync(message)) as UnsubAck;
var rs = (await SendAsync(message).ConfigureAwait(false)) as UnsubAck;
if (rs != null)
{

Expand All @@ -581,7 +581,7 @@ private void Client_Closed(Object sender, EventArgs e)

var message = new PingRequest();

var rs = (await SendAsync(message)) as PingResponse;
var rs = (await SendAsync(message).ConfigureAwait(false)) as PingResponse;
return rs;
}

Expand Down
6 changes: 4 additions & 2 deletions NewLife.MQTT/NewLife.MQTT.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
<Nullable>enable</Nullable>
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\Doc\newlife.snk</AssemblyOriginatorKeyFile>
<AnalysisLevel>latest</AnalysisLevel>
<WarningsAsErrors>CA2007</WarningsAsErrors>
</PropertyGroup>

<PropertyGroup>
Expand Down Expand Up @@ -65,8 +67,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Remoting" Version="3.2.2024.1116" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
<PackageReference Include="NewLife.Remoting" Version="3.2.2024.1124-beta1544" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion NewLife.MqttServer/NewLife.MqttServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
<PackageReference Include="NewLife.Stardust" Version="3.2.2024.1117" />
</ItemGroup>

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,27 +76,27 @@ var client = new MqttClient
ClientId = Guid.NewGuid() + "",
};

await client.ConnectAsync();
await client.ConnectAsync().ConfigureAwait(false);

// 订阅“/test”主题
var rt = await client.SubscribeAsync("/test", (e) =>
{
XTrace.WriteLine("收到消息:" + "/test/# =>" + e.Topic + ":" + e.Payload.ToStr());
});
}).ConfigureAwait(false);

// 每2秒向“/test”主题发布一条消息
while (true)
{
try
{
var msg = "学无先后达者为师" + Rand.NextString(8);
await client.PublishAsync("/test", msg);
await client.PublishAsync("/test", msg).ConfigureAwait(false);
}
catch (Exception ex)
{
XTrace.WriteException(ex);
}
await Task.Delay(2000);
await Task.Delay(2000).ConfigureAwait(false);
}
```
客户端连接服务端有几个要素:`服务端地址``用户名``密码``客户端标识`,然后通过`ConnectAsync`连接服务端。
Expand Down
2 changes: 1 addition & 1 deletion Test/Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NewLife.MQTT\NewLife.MQTT.csproj" />
Expand Down
2 changes: 1 addition & 1 deletion XUnitTestClient/XUnitTestClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
<PackageReference Include="NewLife.UnitTest" Version="1.0.2024.1006" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
Expand Down

0 comments on commit bbc3494

Please sign in to comment.