Skip to content

Commit

Permalink
强制ConfigureAwait(false)
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Nov 30, 2024
1 parent 5c8cf97 commit facca46
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 69 deletions.
12 changes: 6 additions & 6 deletions NewLife.Remoting.Extensions/Controllers/BaseDeviceController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,9 @@ public virtual async Task Notify()

if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var socket = await HttpContext.WebSockets.AcceptWebSocketAsync();
using var socket = await HttpContext.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);

await HandleNotify(socket, Token);
await HandleNotify(socket, Token).ConfigureAwait(false);
}
else
HttpContext.Response.StatusCode = 400;
Expand Down Expand Up @@ -231,7 +231,7 @@ await socket.WaitForClose(txt =>
// 长连接上线。可能客户端心跳已经停了,WS还在,这里重新上线
_deviceService.SetOnline(device, true, token, ip);
}
}, source);
}, source).ConfigureAwait(false);

WriteLog("WebSocket断开", true, $"State={socket.State} CloseStatus={socket.CloseStatus} sid={sid} Remote={remote}");

Expand All @@ -248,7 +248,7 @@ private async Task ConsumeMessage(WebSocket socket, String code, IProducerConsum
while (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open)
{
ISpan? span = null;
var mqMsg = await queue.TakeOneAsync(15, cancellationToken);
var mqMsg = await queue.TakeOneAsync(15, cancellationToken).ConfigureAwait(false);
if (mqMsg != null)
{
// 埋点
Expand All @@ -274,14 +274,14 @@ private async Task ConsumeMessage(WebSocket socket, String code, IProducerConsum
{
WriteLog("WebSocket发送", true, mqMsg);

await socket.SendAsync(mqMsg.GetBytes(), WebSocketMessageType.Text, true, cancellationToken);
await socket.SendAsync(mqMsg.GetBytes(), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
}

span?.Dispose();
}
else
{
await Task.Delay(1_000, cancellationToken);
await Task.Delay(1_000, cancellationToken).ConfigureAwait(false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public async Task BindModelAsync(ModelBindingContext bindingContext)
try
{
var req = bindingContext.HttpContext.Request;
var entityBody = await req.ReadFromJsonAsync(model!.GetType());
var entityBody = await req.ReadFromJsonAsync(model!.GetType()).ConfigureAwait(false);

bindingContext.Result = ModelBindingResult.Success(entityBody);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\Doc\newlife.snk</AssemblyOriginatorKeyFile>
<NoWarn>1701;1702;NU5104;NETSDK1138;CS7035</NoWarn>
<WarningsAsErrors>CA2007</WarningsAsErrors>
</PropertyGroup>

<PropertyGroup>
Expand Down
68 changes: 34 additions & 34 deletions NewLife.Remoting/Clients/ClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ class MyApiClient : ApiClient
{
public ClientBase Client { get; set; } = null!;

protected override async Task<Object?> OnLoginAsync(ISocketClient client, Boolean force, CancellationToken cancellationToken) => await InvokeWithClientAsync<Object>(client, Client.Actions[Features.Login], Client.BuildLoginRequest(), 0, cancellationToken);
protected override Task<Object?> OnLoginAsync(ISocketClient client, Boolean force, CancellationToken cancellationToken) => InvokeWithClientAsync<Object>(client, Client.Actions[Features.Login], Client.BuildLoginRequest(), 0, cancellationToken);
}

/// <summary>异步调用。HTTP默认POST,自动识别GET</summary>
Expand All @@ -284,10 +284,10 @@ protected virtual async Task<TResult> OnInvokeAsync<TResult>(String action, Obje
if (args == null || args.GetType().IsBaseType() || action.StartsWithIgnoreCase("Get") || action.ToLower().Contains("/get"))
method = HttpMethod.Get;

rs = await http.InvokeAsync<TResult>(method, action, args, null, cancellationToken);
rs = await http.InvokeAsync<TResult>(method, action, args, null, cancellationToken).ConfigureAwait(false);
}
else
rs = await _client.InvokeAsync<TResult>(action, args, cancellationToken);
rs = await _client.InvokeAsync<TResult>(action, args, cancellationToken).ConfigureAwait(false);

if (Log != null && Log.Level <= LogLevel.Debug) WriteLog("[{0}]<={1}", action, rs is IPacket or Byte[]? "" : rs?.ToJson());

Expand All @@ -311,10 +311,10 @@ protected virtual async Task<TResult> GetAsync<TResult>(String action, Object? a

// 验证登录
var needLogin = !Actions[Features.Login].EqualIgnoreCase(action);
if (!Logined && needLogin && Features.HasFlag(Features.Login)) await Login(cancellationToken);
if (!Logined && needLogin && Features.HasFlag(Features.Login)) await Login(cancellationToken).ConfigureAwait(false);

// GET请求
var rs = await http.InvokeAsync<TResult>(HttpMethod.Get, action, args, null, cancellationToken);
var rs = await http.InvokeAsync<TResult>(HttpMethod.Get, action, args, null, cancellationToken).ConfigureAwait(false);

if (Log != null && Log.Level <= LogLevel.Debug) WriteLog("[{0}]<={1}", action, rs is IPacket or Byte[]? "" : rs?.ToJson());

Expand All @@ -334,11 +334,11 @@ protected virtual async Task<TResult> GetAsync<TResult>(String action, Object? a
{
// 验证登录。如果该接口需要登录,且未登录,则先登录
var needLogin = !Actions[Features.Login].EqualIgnoreCase(action);
if (needLogin && !Logined && Features.HasFlag(Features.Login)) await Login(cancellationToken);
if (needLogin && !Logined && Features.HasFlag(Features.Login)) await Login(cancellationToken).ConfigureAwait(false);

try
{
return await OnInvokeAsync<TResult>(action, args, cancellationToken);
return await OnInvokeAsync<TResult>(action, args, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand All @@ -353,10 +353,10 @@ protected virtual async Task<TResult> GetAsync<TResult>(String action, Object? a
{
Log?.Debug("{0}", ex);
WriteLog("重新登录,因调用[{0}]失败:{1}", action, ex.Message);
await Login(cancellationToken);
await Login(cancellationToken).ConfigureAwait(false);

// 再次执行当前请求
return await OnInvokeAsync<TResult>(action, args, cancellationToken);
return await OnInvokeAsync<TResult>(action, args, cancellationToken).ConfigureAwait(false);
}
}

Expand Down Expand Up @@ -410,7 +410,7 @@ private async Task TryConnectServer(Object state)
var timer = _timerLogin;
try
{
if (!Logined) await Login();
if (!Logined) await Login().ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -443,7 +443,7 @@ private async Task TryConnectServer(Object state)
{
for (var i = 0; i < 50; i++)
{
await TaskEx.Delay(100);
await TaskEx.Delay(100, cancellationToken).ConfigureAwait(false);
if (Status == LoginStatus.LoggedIn) return null;
if (Status != LoginStatus.LoggingIn) break;
}
Expand All @@ -465,7 +465,7 @@ private async Task TryConnectServer(Object state)
// 登录前清空令牌,避免服务端使用上一次信息
SetToken(null);

response = await LoginAsync(request, cancellationToken);
response = await LoginAsync(request, cancellationToken).ConfigureAwait(false);
if (response == null) return null;

WriteLog("登录成功:{0}", response);
Expand Down Expand Up @@ -586,7 +586,7 @@ protected virtual void FillLoginRequest(ILoginRequest request)

try
{
var rs = await LogoutAsync(reason, cancellationToken);
var rs = await LogoutAsync(reason, cancellationToken).ConfigureAwait(false);

// 更新令牌
SetToken(rs?.Token);
Expand Down Expand Up @@ -617,9 +617,9 @@ protected virtual void FillLoginRequest(ILoginRequest request)
protected virtual async Task<ILogoutResponse?> LogoutAsync(String? reason, CancellationToken cancellationToken)
{
if (_client is ApiHttpClient)
return await GetAsync<ILogoutResponse>(Actions[Features.Logout], new { reason }, cancellationToken);
return await GetAsync<ILogoutResponse>(Actions[Features.Logout], new { reason }, cancellationToken).ConfigureAwait(false);

return await InvokeAsync<ILogoutResponse>(Actions[Features.Logout], new { reason }, cancellationToken);
return await InvokeAsync<ILogoutResponse>(Actions[Features.Logout], new { reason }, cancellationToken).ConfigureAwait(false);
}
#endregion

Expand Down Expand Up @@ -651,7 +651,7 @@ protected virtual void FillLoginRequest(ILoginRequest request)
IPingResponse? response = null;
try
{
response = await PingAsync(request, cancellationToken);
response = await PingAsync(request, cancellationToken).ConfigureAwait(false);
if (response != null)
{
// 由服务器改变采样频率
Expand All @@ -667,7 +667,7 @@ protected virtual void FillLoginRequest(ILoginRequest request)
{
foreach (var model in response.Commands)
{
await ReceiveCommand(model, "Pong", cancellationToken);
await ReceiveCommand(model, "Pong", cancellationToken).ConfigureAwait(false);
}
}
}
Expand All @@ -684,7 +684,7 @@ protected virtual void FillLoginRequest(ILoginRequest request)
// 上报正常,处理历史,失败则丢弃
while (_fails.TryDequeue(out var info))
{
await PingAsync(info, cancellationToken);
await PingAsync(info, cancellationToken).ConfigureAwait(false);
}

return response;
Expand All @@ -700,7 +700,7 @@ protected virtual void FillLoginRequest(ILoginRequest request)
if (Features.HasFlag(Features.Login))
{
WriteLog("重新登录,因心跳失败:{0}", ex.Message);
await Login(cancellationToken);
await Login(cancellationToken).ConfigureAwait(false);
}

return null;
Expand Down Expand Up @@ -776,14 +776,14 @@ private async Task CheckUpgrade(Object? data)
{
if (!NetworkInterface.GetIsNetworkAvailable()) return;

await Upgrade(null);
await Upgrade(null).ConfigureAwait(false);
}

private async Task<String?> ReceiveUpgrade(String? arguments)
{
// 参数作为通道
var channel = arguments;
var rs = await Upgrade(channel);
var rs = await Upgrade(channel).ConfigureAwait(false);
if (rs == null) return "没有可用更新!";

return $"成功更新到[{rs.Version}]";
Expand All @@ -802,7 +802,7 @@ private async Task CheckUpgrade(Object? data)
ug.DeleteBackup(".");

// 调用接口查询思否存在更新信息
var info = await UpgradeAsync(channel, cancellationToken);
var info = await UpgradeAsync(channel, cancellationToken).ConfigureAwait(false);
if (info == null || info.Version == _lastVersion) return info;

// _lastVersion避免频繁更新同一个版本
Expand All @@ -813,7 +813,7 @@ private async Task CheckUpgrade(Object? data)
{
// 下载文件包
ug.Url = BuildUrl(info.Source!);
await ug.Download(cancellationToken);
await ug.Download(cancellationToken).ConfigureAwait(false);

// 检查文件完整性
if (!info.FileHash.IsNullOrEmpty() && !ug.CheckFileHash(info.FileHash))
Expand Down Expand Up @@ -905,9 +905,9 @@ protected virtual void Restart(Upgrade upgrade)
protected virtual async Task<IUpgradeInfo?> UpgradeAsync(String? channel, CancellationToken cancellationToken)
{
if (_client is ApiHttpClient)
return await GetAsync<IUpgradeInfo>(Actions[Features.Upgrade], new { channel }, cancellationToken);
return await GetAsync<IUpgradeInfo>(Actions[Features.Upgrade], new { channel }, cancellationToken).ConfigureAwait(false);

return await InvokeAsync<IUpgradeInfo>(Actions[Features.Upgrade], new { channel }, cancellationToken);
return await InvokeAsync<IUpgradeInfo>(Actions[Features.Upgrade], new { channel }, cancellationToken).ConfigureAwait(false);
}
#endregion

Expand Down Expand Up @@ -958,7 +958,7 @@ protected virtual async Task OnPing(Object state)
using var span = Tracer?.NewSpan(Name + "Ping");
try
{
if (Features.HasFlag(Features.Ping)) await Ping();
if (Features.HasFlag(Features.Ping)) await Ping().ConfigureAwait(false);

if (_client is ApiHttpClient http && Features.HasFlag(Features.Notify))
{
Expand All @@ -968,7 +968,7 @@ protected virtual async Task OnPing(Object state)
#else
_ws ??= new WsChannel(this);
#endif
if (_ws != null) await _ws.ValidWebSocket(http);
if (_ws != null) await _ws.ValidWebSocket(http).ConfigureAwait(false);
}
}
catch (Exception ex)
Expand Down Expand Up @@ -1024,19 +1024,19 @@ protected virtual async Task OnPing(Object state)
};

if (Features.HasFlag(Features.CommandReply))
await CommandReply(reply, cancellationToken);
await CommandReply(reply, cancellationToken).ConfigureAwait(false);

return reply;
}
else
return await OnReceiveCommand(model, cancellationToken);
return await OnReceiveCommand(model, cancellationToken).ConfigureAwait(false);
}
else
{
var reply = new CommandReplyModel { Id = model.Id, Status = CommandStatus.取消 };

if (Features.HasFlag(Features.CommandReply))
await CommandReply(reply, cancellationToken);
await CommandReply(reply, cancellationToken).ConfigureAwait(false);

return reply;
}
Expand All @@ -1057,11 +1057,11 @@ protected virtual async Task OnPing(Object state)
var e = new CommandEventArgs { Model = model };
Received?.Invoke(this, e);

var rs = await this.ExecuteCommand(model, cancellationToken);
var rs = await this.ExecuteCommand(model, cancellationToken).ConfigureAwait(false);
e.Reply ??= rs;

if (e.Reply != null && e.Reply.Id > 0 && Features.HasFlag(Features.CommandReply))
await CommandReply(e.Reply, cancellationToken);
await CommandReply(e.Reply, cancellationToken).ConfigureAwait(false);

return e.Reply;
}
Expand All @@ -1071,7 +1071,7 @@ protected virtual async Task OnPing(Object state)
/// <param name="argument"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<CommandReplyModel?> SendCommand(String command, String argument, CancellationToken cancellationToken = default) => await OnReceiveCommand(new CommandModel { Command = command, Argument = argument }, cancellationToken);
public virtual Task<CommandReplyModel?> SendCommand(String command, String argument, CancellationToken cancellationToken = default) => OnReceiveCommand(new CommandModel { Command = command, Argument = argument }, cancellationToken);

/// <summary>上报命令调用结果</summary>
/// <param name="model"></param>
Expand Down Expand Up @@ -1120,7 +1120,7 @@ async Task DoPostEvent(Object state)
if (tid != null) span?.Detach(tid);
try
{
if (list.Count > 0) await PostEvents(list.ToArray());
if (list.Count > 0) await PostEvents(list.ToArray()).ConfigureAwait(false);

// 成功后读取本地缓存
while (_failEvents.TryDequeue(out var ev))
Expand Down
13 changes: 7 additions & 6 deletions NewLife.Remoting/Clients/ICommandClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public static async Task<CommandReplyModel> ExecuteCommand(this ICommandClient c
var rs = new CommandReplyModel { Id = model.Id, Status = CommandStatus.已完成 };
try
{
var result = await OnCommand(client, model, cancellationToken);
var result = await OnCommand(client, model, cancellationToken).ConfigureAwait(false);
if (result is CommandReplyModel reply)
{
reply.Id = model.Id;
Expand Down Expand Up @@ -152,16 +152,17 @@ public static async Task<CommandReplyModel> ExecuteCommand(this ICommandClient c
if (!client.Commands.TryGetValue(model.Command, out var d))
throw new ApiException(ApiCode.NotFound, $"找不到服务[{model.Command}]");

if (d is Func<String?, Task<String?>> func1) return await func1(model.Argument);
//if (d is Func<String, Task<Object>> func2) return await func2(model.Argument);
if (d is Func<CommandModel, Task<CommandReplyModel>> func3) return await func3(model);
if (d is Func<CommandModel, CancellationToken, Task<CommandReplyModel>> func4) return await func4(model, cancellationToken);
if (d is Func<String?, Task<String?>> func1)
return await func1(model.Argument).ConfigureAwait(false);
if (d is Func<CommandModel, Task<CommandReplyModel>> func3)
return await func3(model).ConfigureAwait(false);
if (d is Func<CommandModel, CancellationToken, Task<CommandReplyModel>> func4)
return await func4(model, cancellationToken).ConfigureAwait(false);

if (d is Action<CommandModel> func21) func21(model);

if (d is Func<CommandModel, CommandReplyModel> func31) return func31(model);
if (d is Func<String?, String?> func32) return func32(model.Argument);
//if (d is Func<String, Object> func33) return func33(model.Argument);

//return null;
throw new ApiException(ApiCode.InternalServerError, $"服务[{model.Command}]的签名[{d}]不正确");
Expand Down
8 changes: 4 additions & 4 deletions NewLife.Remoting/Clients/Upgrade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ public virtual async Task<Boolean> Download(CancellationToken cancellationToken
var sw = Stopwatch.StartNew();

var web = CreateClient();
//await web.DownloadFileAsync(url, file);
file = await DownloadFileAsync(web, url, file, cancellationToken);
file = await DownloadFileAsync(web, url, file, cancellationToken).ConfigureAwait(false);

sw.Stop();
WriteLog("下载完成!{2} 大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds, file);
Expand Down Expand Up @@ -341,7 +340,7 @@ private HttpClient CreateClient()
public static async Task<String> DownloadFileAsync(HttpClient client, String address, String fileName, CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Get, address);
var rs = await client.SendAsync(request, cancellationToken);
var rs = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
rs.EnsureSuccessStatusCode();

// 从Http响应头中获取文件名
Expand All @@ -359,7 +358,8 @@ public static async Task<String> DownloadFileAsync(HttpClient client, String add

var ms = rs.Content;
using var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
await ms.CopyToAsync(fs);
await ms.CopyToAsync(fs).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);

// 截断文件,如果前面删除失败,这里就可能使用旧文件,需要把多余部分截断
fs.SetLength(fs.Position);
Expand Down
Loading

0 comments on commit facca46

Please sign in to comment.