为了提升性能,在同步调用异步时规避卡UI上下文,所有await状态机都设置ConfigureAwait(false),开启CA2007并视为编译错误

This commit is contained in:
大石头 2024-12-02 11:06:30 +08:00
parent 54a6900769
commit 60a6f7cfd3
20 changed files with 60 additions and 56 deletions

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -107,7 +107,7 @@ class CacheFileProvider : IFileProvider
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));
}
@ -138,7 +138,7 @@ class CacheFileProvider : IFileProvider
{
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);
@ -248,7 +248,7 @@ class CacheFileProvider : IFileProvider
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

View File

@ -46,7 +46,7 @@ public class IpFilterMiddleware
}
}
await _next.Invoke(ctx);
await _next.Invoke(ctx).ConfigureAwait(false);
}
Boolean ValidIP(String ip)

View File

@ -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>

View File

@ -58,7 +58,7 @@ public class TracerMiddleware
{
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;
@ -91,7 +91,7 @@ public class TracerMiddleware
try
{
await _next.Invoke(ctx);
await _next.Invoke(ctx).ConfigureAwait(false);
// 自动记录用户访问主机地址
SaveServiceAddress(ctx);
@ -119,7 +119,7 @@ public class TracerMiddleware
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;

View File

@ -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>

View File

@ -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>

View File

@ -174,7 +174,7 @@ public class AppClient : ClientBase, IRegistry
if (_appInfo == null) return null;
return await local.PingAsync(_appInfo, WatchdogTimeout);
return await local.PingAsync(_appInfo, WatchdogTimeout).ConfigureAwait(false);
}
/// <summary>心跳</summary>
@ -187,13 +187,13 @@ public class AppClient : ClientBase, IRegistry
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)
{
@ -214,17 +214,17 @@ public class AppClient : ClientBase, IRegistry
// 如果没有设置地址,则不要调用接口
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)
@ -284,7 +284,7 @@ public class AppClient : ClientBase, IRegistry
service.Tag = tag;
service.Health = health;
var rs = await RegisterAsync(service);
var rs = await RegisterAsync(service).ConfigureAwait(false);
WriteLog("注册完成 {0}", rs?.ToJson());
return service;
@ -328,7 +328,7 @@ public class AppClient : ClientBase, IRegistry
/// <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>
@ -356,7 +356,7 @@ public class AppClient : ClientBase, IRegistry
// 消费即使报错,也要往下走,借助缓存
try
{
var models = await ResolveAsync(service);
var models = await ResolveAsync(service).ConfigureAwait(false);
if (models != null && models.Length > 0)
{
_consumes[serviceName] = models;
@ -405,7 +405,7 @@ public class AppClient : ClientBase, IRegistry
if (!address.IsNullOrEmpty()) svc.Address = address;
}
if (!svc.Address.IsNullOrEmpty()) await RegisterAsync(svc);
if (!svc.Address.IsNullOrEmpty()) await RegisterAsync(svc).ConfigureAwait(false);
}
}
@ -415,7 +415,7 @@ public class AppClient : ClientBase, IRegistry
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;
@ -473,7 +473,7 @@ public class AppClient : ClientBase, IRegistry
private async Task<String?> DoRefresh(String? argument)
{
await RefreshConsume();
await RefreshConsume().ConfigureAwait(false);
return "刷新服务成功";
}

View File

@ -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>

View File

@ -103,7 +103,7 @@ public class LocalStarClient
try
{
return Info = await _client.InvokeAsync<AgentInfo>("Info", _local);
return Info = await _client.InvokeAsync<AgentInfo>("Info", _local).ConfigureAwait(false);
}
catch (TimeoutException)
{
@ -117,7 +117,7 @@ public class LocalStarClient
/// <summary>向StarAgent发送心跳</summary>
/// <returns></returns>
public async Task<PingResponse?> PingAsync(AppInfo appInfo, Int32 watchdogTimeout)
public Task<PingResponse?> PingAsync(AppInfo appInfo, Int32 watchdogTimeout)
{
Init();
@ -131,7 +131,7 @@ public class LocalStarClient
WatchdogTimeout = watchdogTimeout,
};
return await _client.InvokeAsync<PingResponse>("Ping", info);
return _client.InvokeAsync<PingResponse>("Ping", info);
}
#endregion

View File

@ -215,12 +215,12 @@ public class FrameworkManager
{
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);
});
}
}

View File

@ -91,7 +91,7 @@ public static class RegistryExtensions
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);
@ -176,15 +176,15 @@ public static class RegistryExtensions
/// <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);

View File

@ -345,7 +345,7 @@ public class StarClient : ClientBase, ICommandClient, IEventProvider
/// <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)
{
// 迁移到新服务器
@ -356,13 +356,13 @@ public class StarClient : ClientBase, ICommandClient, IEventProvider
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);
}
}
}
@ -374,16 +374,16 @@ public class StarClient : ClientBase, ICommandClient, IEventProvider
#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
}

View File

@ -462,11 +462,11 @@ public class StarFactory : DisposeBase
/// <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,
@ -485,11 +485,11 @@ public class StarFactory : DisposeBase
/// <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,

View File

@ -20,6 +20,8 @@
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\Doc\newlife.snk</AssemblyOriginatorKeyFile>
<NoWarn>1701;1702;NU5104;NU1505;NETSDK1138;CS7035</NoWarn>
<AnalysisLevel>latest</AnalysisLevel>
<WarningsAsErrors>CA2007</WarningsAsErrors>
</PropertyGroup>
<PropertyGroup>
@ -117,10 +119,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Remoting" Version="3.2.2024.1116" />
<PackageReference Include="NewLife.Remoting" Version="3.2.2024.1202" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1201" />
</ItemGroup>
</Project>

View File

@ -18,11 +18,11 @@ public class WeiXinClient
#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>

View File

@ -30,7 +30,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Win32.SystemEvents" Version="9.0.0" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1115" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1201" />
<PackageReference Include="SSH.NET" Version="2024.2.0" />
</ItemGroup>