Skip to content

Commit

Permalink
为了提升性能,在同步调用异步时规避卡UI上下文,所有await状态机都设置ConfigureAwait(false),开启CA2007并视…
Browse files Browse the repository at this point in the history
…为编译错误
  • Loading branch information
nnhy committed Dec 2, 2024
1 parent 54a6900 commit 60a6f7c
Show file tree
Hide file tree
Showing 20 changed files with 60 additions and 56 deletions.
2 changes: 1 addition & 1 deletion Plugins/MySqlAgent/MySqlAgent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NewLife.XCode" Version="11.16.2024.1114" />
<PackageReference Include="NewLife.XCode" Version="11.16.2024.1202" />
</ItemGroup>

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

<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1201" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion Samples/TestB/TestB.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1201" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion Stardust.Data/Stardust.Data.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="NewLife.XCode" Version="11.16.2024.1114" />
<PackageReference Include="NewLife.XCode" Version="11.16.2024.1202" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions Stardust.Extensions/Caches/CacheFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public IFileInfo GetFileInfo(String subpath)
if (Path.GetFileName(fullPath).Contains('.'))
{
if (!fi.Exists)
fi = DownloadFile(subpath, fullPath).Result?.AsFile();
fi = DownloadFile(subpath, fullPath).ConfigureAwait(false).GetAwaiter().GetResult()?.AsFile();
else if (fi.LastWriteTime.AddMonths(1) < DateTime.Now)
_ = Task.Run(() => DownloadFile(subpath, fullPath));
}
Expand Down Expand Up @@ -138,7 +138,7 @@ public IFileInfo GetFileInfo(String subpath)
{
using var fs = new FileStream(tmp, FileMode.OpenOrCreate);
using var client = new HttpClient { Timeout = Timeout };
using var rs = await client.GetStreamAsync(url);
using var rs = await client.GetStreamAsync(url).ConfigureAwait(false);
rs.CopyTo(fs);
fs.Flush();
fs.SetLength(fs.Position);
Expand Down Expand Up @@ -248,7 +248,7 @@ public IDirectoryContents GetDirectoryContents(String subpath)
XTrace.WriteLine("下载目录:{0}", url);

using var client = new HttpClient { Timeout = Timeout };
var html = await client.GetStringAsync(url);
var html = await client.GetStringAsync(url).ConfigureAwait(false);

var links = Link.Parse(html, url);
var list = links.Select(e => new FileInfoModel
Expand Down
2 changes: 1 addition & 1 deletion Stardust.Extensions/IpFilterMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public async Task Invoke(HttpContext ctx)
}
}

await _next.Invoke(ctx);
await _next.Invoke(ctx).ConfigureAwait(false);
}

Boolean ValidIP(String ip)
Expand Down
2 changes: 2 additions & 0 deletions Stardust.Extensions/Stardust.Extensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\Doc\newlife.snk</AssemblyOriginatorKeyFile>
<NoWarn>1701;1702;NU5104;NETSDK1138;CS7035</NoWarn>
<AnalysisLevel>latest</AnalysisLevel>
<WarningsAsErrors>CA2007</WarningsAsErrors>
</PropertyGroup>

<PropertyGroup>
Expand Down
6 changes: 3 additions & 3 deletions Stardust.Extensions/TracerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public async Task Invoke(HttpContext ctx)
{
req.EnableBuffering();

var count = await req.Body.ReadAsync(buf, 0, buf.Length);
var count = await req.Body.ReadAsync(buf, 0, buf.Length).ConfigureAwait(false);
span.AppendTag("\r\n<=\r\n" + buf.ToStr(null, 0, count));
req.Body.Position = 0;
flag = true;
Expand Down Expand Up @@ -91,7 +91,7 @@ public async Task Invoke(HttpContext ctx)

try
{
await _next.Invoke(ctx);
await _next.Invoke(ctx).ConfigureAwait(false);

// 自动记录用户访问主机地址
SaveServiceAddress(ctx);
Expand Down Expand Up @@ -119,7 +119,7 @@ public async Task Invoke(HttpContext ctx)
try
{
var p = res.Body.Position;
var count = await res.Body.ReadAsync(buf, 0, buf.Length);
var count = await res.Body.ReadAsync(buf, 0, buf.Length).ConfigureAwait(false);
span.AppendTag("\r\n=>\r\n" + buf.ToStr(null, 0, count));
res.Body.Position = p;
flag = true;
Expand Down
2 changes: 1 addition & 1 deletion Stardust.Server/Stardust.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<ItemGroup>
<PackageReference Include="NewLife.IP" Version="2.2.2024.1102" />
<PackageReference Include="NewLife.Redis" Version="6.0.2024.1101" />
<PackageReference Include="NewLife.Remoting.Extensions" Version="3.2.2024.1116" />
<PackageReference Include="NewLife.Remoting.Extensions" Version="3.2.2024.1202" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Stardust.Web/Stardust.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
<PackageReference Include="NewLife.Cube.Core" Version="6.2.2024.1115" />
<PackageReference Include="NewLife.IP" Version="2.2.2024.1102" />
<PackageReference Include="NewLife.Redis" Version="6.0.2024.1101" />
<PackageReference Include="NewLife.Remoting.Extensions" Version="3.2.2024.1116" />
<PackageReference Include="NewLife.Remoting.Extensions" Version="3.2.2024.1202" />
</ItemGroup>

<ItemGroup>
Expand Down
28 changes: 14 additions & 14 deletions Stardust/AppClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public override IPingRequest BuildPingRequest()

if (_appInfo == null) return null;

return await local.PingAsync(_appInfo, WatchdogTimeout);
return await local.PingAsync(_appInfo, WatchdogTimeout).ConfigureAwait(false);
}

/// <summary>心跳</summary>
Expand All @@ -187,13 +187,13 @@ protected override async Task OnPing(Object state)
try
{
// 向服务端发送心跳后,再向本地发送心跳
await base.OnPing(state);
await PingLocal();
await base.OnPing(state).ConfigureAwait(false);
await PingLocal().ConfigureAwait(false);

if (!NetworkInterface.GetIsNetworkAvailable()) return;

await RefreshPublish();
await RefreshConsume();
await RefreshPublish().ConfigureAwait(false);
await RefreshConsume().ConfigureAwait(false);
}
catch (Exception ex)
{
Expand All @@ -214,17 +214,17 @@ protected override async Task OnPing(Object state)
// 如果没有设置地址,则不要调用接口
if (service.Address.IsNullOrEmpty()) return null;

return await InvokeAsync<ServiceModel>("App/RegisterService", service);
return await InvokeAsync<ServiceModel>("App/RegisterService", service).ConfigureAwait(false);
}

/// <summary>取消服务(底层)</summary>
/// <param name="service">应用服务</param>
/// <returns></returns>
public async Task<ServiceModel?> UnregisterAsync(PublishServiceInfo service)
public Task<ServiceModel?> UnregisterAsync(PublishServiceInfo service)
{
_publishServices.TryRemove(service.ServiceName, out _);

return await InvokeAsync<ServiceModel>("App/UnregisterService", service);
return InvokeAsync<ServiceModel>("App/UnregisterService", service);
}

private void AddService(PublishServiceInfo service)
Expand Down Expand Up @@ -284,7 +284,7 @@ public async Task<PublishServiceInfo> RegisterAsync(String serviceName, String a
service.Tag = tag;
service.Health = health;

var rs = await RegisterAsync(service);
var rs = await RegisterAsync(service).ConfigureAwait(false);
WriteLog("注册完成 {0}", rs?.ToJson());

return service;
Expand Down Expand Up @@ -328,7 +328,7 @@ public PublishServiceInfo Register(String serviceName, Func<String?> addressCall
/// <summary>消费服务(底层)</summary>
/// <param name="service">应用服务</param>
/// <returns></returns>
public async Task<ServiceModel[]?> ResolveAsync(ConsumeServiceInfo service) => await InvokeAsync<ServiceModel[]>("App/ResolveService", service);
public Task<ServiceModel[]?> ResolveAsync(ConsumeServiceInfo service) => InvokeAsync<ServiceModel[]>("App/ResolveService", service);

/// <summary>消费得到服务地址信息</summary>
/// <param name="serviceName">服务名</param>
Expand Down Expand Up @@ -356,7 +356,7 @@ public PublishServiceInfo Register(String serviceName, Func<String?> addressCall
// 消费即使报错,也要往下走,借助缓存
try
{
var models = await ResolveAsync(service);
var models = await ResolveAsync(service).ConfigureAwait(false);
if (models != null && models.Length > 0)
{
_consumes[serviceName] = models;
Expand Down Expand Up @@ -405,7 +405,7 @@ private async Task RefreshPublish()
if (!address.IsNullOrEmpty()) svc.Address = address;
}

if (!svc.Address.IsNullOrEmpty()) await RegisterAsync(svc);
if (!svc.Address.IsNullOrEmpty()) await RegisterAsync(svc).ConfigureAwait(false);
}
}

Expand All @@ -415,7 +415,7 @@ private async Task RefreshConsume()
foreach (var item in _consumeServices)
{
var svc = item.Value;
var ms = await ResolveAsync(svc);
var ms = await ResolveAsync(svc).ConfigureAwait(false);
if (ms != null && ms.Length > 0)
{
_consumes[svc.ServiceName] = ms;
Expand Down Expand Up @@ -473,7 +473,7 @@ public void Attach(ICommandClient client)

private async Task<String?> DoRefresh(String? argument)
{
await RefreshConsume();
await RefreshConsume().ConfigureAwait(false);

return "刷新服务成功";
}
Expand Down
4 changes: 2 additions & 2 deletions Stardust/DingTalk/DingTalkClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ public class DingTalkClient
#endregion

#region 发送消息
private async Task<Object?> PostAsync(Object msg)
private Task<Object?> PostAsync(Object msg)
{
_Client ??= Tracer.CreateHttpClient();

return await _Client.PostAsync<Object>(Url, msg);
return _Client.PostAsync<Object>(Url, msg);
}

/// <summary>发送文本消息</summary>
Expand Down
6 changes: 3 additions & 3 deletions Stardust/LocalStarClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void Init()

try
{
return Info = await _client.InvokeAsync<AgentInfo>("Info", _local);
return Info = await _client.InvokeAsync<AgentInfo>("Info", _local).ConfigureAwait(false);
}
catch (TimeoutException)
{
Expand All @@ -117,7 +117,7 @@ private void Init()

/// <summary>向StarAgent发送心跳</summary>
/// <returns></returns>
public async Task<PingResponse?> PingAsync(AppInfo appInfo, Int32 watchdogTimeout)
public Task<PingResponse?> PingAsync(AppInfo appInfo, Int32 watchdogTimeout)
{
Init();

Expand All @@ -131,7 +131,7 @@ private void Init()
WatchdogTimeout = watchdogTimeout,
};

return await _client.InvokeAsync<PingResponse>("Ping", info);
return _client.InvokeAsync<PingResponse>("Ping", info);
}
#endregion

Expand Down
6 changes: 3 additions & 3 deletions Stardust/Managers/FrameworkManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,12 @@ void CheckPing()
{
TaskEx.Run(async () =>
{
await client.Ping();
await TaskEx.Delay(1000);
await client.Ping().ConfigureAwait(false);
await TaskEx.Delay(1000).ConfigureAwait(false);

//!! 要执行整个升级动作,而不仅仅是拉取新版本
//await client.Upgrade("", "");
await client.SendCommand("node/upgrade", "");
await client.SendCommand("node/upgrade", "").ConfigureAwait(false);
});
}
}
Expand Down
8 changes: 4 additions & 4 deletions Stardust/Registry/IRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public static async Task<IApiClient> CreateForServiceAsync(this IRegistry regist
if (registry is ILogFeature logFeature) http.Log = logFeature.Log;
if (registry is ITracerFeature tracerFeature) http.Tracer = tracerFeature.Tracer;

var models = await registry.ResolveAsync(serviceName, null, tag);
var models = await registry.ResolveAsync(serviceName, null, tag).ConfigureAwait(false);

if (models != null) BindServices(http, models);

Expand Down Expand Up @@ -176,15 +176,15 @@ public static void BindServices(this ApiHttpClient client, ServiceModel[] ms)
/// <returns></returns>
public static async Task<String[]> ResolveAddressAsync(this IRegistry registry, String serviceName, String? minVersion = null, String? tag = null)
{
var ms = await registry.ResolveAsync(serviceName, minVersion, tag);
if (ms == null) return new String[0];
var ms = await registry.ResolveAsync(serviceName, minVersion, tag).ConfigureAwait(false);
if (ms == null) return [];

var addrs = new List<String>();
foreach (var item in ms)
{
if (!item.Address.IsNullOrEmpty())
{
var ss = item.Address.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
var ss = item.Address.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries);
foreach (var elm in ss)
{
if (!elm.IsNullOrEmpty() && !addrs.Contains(elm)) addrs.Add(elm);
Expand Down
12 changes: 6 additions & 6 deletions Stardust/StarClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ public override IPingRequest BuildPingRequest()
/// <returns></returns>
public override async Task<IPingResponse?> Ping(CancellationToken cancellationToken = default)
{
var rs = await base.Ping(cancellationToken);
var rs = await base.Ping(cancellationToken).ConfigureAwait(false);
if (rs != null)
{
// 迁移到新服务器
Expand All @@ -356,13 +356,13 @@ public override IPingRequest BuildPingRequest()
OnMigration?.Invoke(this, arg);
if (!arg.Cancel)
{
await Logout("切换新服务器", cancellationToken);
await Logout("切换新服务器", cancellationToken).ConfigureAwait(false);

// 清空原有链接,添加新链接
Server = prs.NewServer;
Client = null;

await Login(cancellationToken);
await Login(cancellationToken).ConfigureAwait(false);
}
}
}
Expand All @@ -374,16 +374,16 @@ public override IPingRequest BuildPingRequest()
#region 部署
/// <summary>获取分配到本节点的应用服务信息</summary>
/// <returns></returns>
public async Task<DeployInfo[]?> GetDeploy() => await InvokeAsync<DeployInfo[]>("Deploy/GetAll");
public Task<DeployInfo[]?> GetDeploy() => InvokeAsync<DeployInfo[]>("Deploy/GetAll");

/// <summary>上传本节点的所有应用服务信息</summary>
/// <param name="services"></param>
/// <returns></returns>
public async Task<Int32> UploadDeploy(ServiceInfo[] services) => await InvokeAsync<Int32>("Deploy/Upload", services);
public Task<Int32> UploadDeploy(ServiceInfo[] services) => InvokeAsync<Int32>("Deploy/Upload", services);

/// <summary>应用心跳。上报应用信息</summary>
/// <param name="inf"></param>
/// <returns></returns>
public async Task<Int32> AppPing(AppInfo inf) => await InvokeAsync<Int32>("Deploy/Ping", inf);
public Task<Int32> AppPing(AppInfo inf) => InvokeAsync<Int32>("Deploy/Ping", inf);
#endregion
}
12 changes: 6 additions & 6 deletions Stardust/StarFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -462,11 +462,11 @@ public IRegistry? Service
/// <param name="expire"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public async Task<Int32> SendNodeCommand(String nodeCode, String command, String? argument = null, Int32 startTime = 0, Int32 expire = 3600, Int32 timeout = 5)
public Task<Int32> SendNodeCommand(String nodeCode, String command, String? argument = null, Int32 startTime = 0, Int32 expire = 3600, Int32 timeout = 5)
{
if (!Valid()) return -1;
if (!Valid()) return Task.FromResult(-1);

return await _client.InvokeAsync<Int32>("Node/SendCommand", new CommandInModel
return _client.InvokeAsync<Int32>("Node/SendCommand", new CommandInModel
{
Code = nodeCode,
Command = command,
Expand All @@ -485,11 +485,11 @@ public async Task<Int32> SendNodeCommand(String nodeCode, String command, String
/// <param name="expire"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public async Task<Int32> SendAppCommand(String appId, String command, String? argument = null, Int32 startTime = 0, Int32 expire = 3600, Int32 timeout = 5)
public Task<Int32> SendAppCommand(String appId, String command, String? argument = null, Int32 startTime = 0, Int32 expire = 3600, Int32 timeout = 5)
{
if (!Valid()) return -1;
if (!Valid()) return Task.FromResult(-1);

return await _client.InvokeAsync<Int32>("App/SendCommand", new CommandInModel
return _client.InvokeAsync<Int32>("App/SendCommand", new CommandInModel
{
Code = appId,
Command = command,
Expand Down
Loading

0 comments on commit 60a6f7c

Please sign in to comment.