Skip to content

Commit

Permalink
[fix]修正网络库SessionBase.SendMessageAsync被同步调用时阻塞UI上下文的问题,使用 await sourc…
Browse files Browse the repository at this point in the history
…e.Task.ConfigureAwait(false)
  • Loading branch information
nnhy committed Nov 23, 2024
1 parent 37db1a3 commit aba0005
Show file tree
Hide file tree
Showing 15 changed files with 64 additions and 64 deletions.
4 changes: 2 additions & 2 deletions NewLife.Core/Caching/MemoryCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -991,7 +991,7 @@ public IEnumerable<T> Take(Int32 count = 1)
{
if (timeout <= 0) return default;

if (!await _occupiedNodes.WaitAsync(timeout * 1000)) return default;
if (!await _occupiedNodes.WaitAsync(timeout * 1000).ConfigureAwait(false)) return default;
}

return _collection.TryTake(out var item) ? item : default;
Expand All @@ -1007,7 +1007,7 @@ public IEnumerable<T> Take(Int32 count = 1)
{
if (timeout <= 0) return default;

if (!await _occupiedNodes.WaitAsync(timeout * 1000, cancellationToken)) return default;
if (!await _occupiedNodes.WaitAsync(timeout * 1000, cancellationToken).ConfigureAwait(false)) return default;
}

return _collection.TryTake(out var item) ? item : default;
Expand Down
20 changes: 10 additions & 10 deletions NewLife.Core/Data/DbTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,8 +525,8 @@ public async Task WriteXml(Stream stream)
};
using var writer = XmlWriter.Create(stream, set);

await writer.WriteStartDocumentAsync();
await writer.WriteStartElementAsync(null, "DbTable", null);
await writer.WriteStartDocumentAsync().ConfigureAwait(false);
await writer.WriteStartElementAsync(null, "DbTable", null).ConfigureAwait(false);

var cs = Columns ?? throw new ArgumentNullException(nameof(Columns));
var ts = Types ?? throw new ArgumentNullException(nameof(Types));
Expand All @@ -536,11 +536,11 @@ public async Task WriteXml(Stream stream)
{
foreach (var row in rows)
{
await writer.WriteStartElementAsync(null, "Table", null);
await writer.WriteStartElementAsync(null, "Table", null).ConfigureAwait(false);
for (var i = 0; i < cs.Length; i++)
{
//await writer.WriteElementStringAsync(null, Columns[i], null, row[i] + "");
await writer.WriteStartElementAsync(null, cs[i], null);
await writer.WriteStartElementAsync(null, cs[i], null).ConfigureAwait(false);

//writer.WriteValue(row[i]);
if (ts[i] == typeof(Boolean))
Expand All @@ -550,18 +550,18 @@ public async Task WriteXml(Stream stream)
else if (ts[i] == typeof(DateTimeOffset))
writer.WriteValue(row[i].ChangeType<DateTimeOffset>());
else if (row[i] is IFormattable ft)
await writer.WriteStringAsync(ft + "");
await writer.WriteStringAsync(ft + "").ConfigureAwait(false);
else
await writer.WriteStringAsync(row[i] + "");
await writer.WriteStringAsync(row[i] + "").ConfigureAwait(false);

await writer.WriteEndElementAsync();
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
await writer.WriteEndElementAsync();
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
}

await writer.WriteEndElementAsync();
await writer.WriteEndDocumentAsync();
await writer.WriteEndElementAsync().ConfigureAwait(false);
await writer.WriteEndDocumentAsync().ConfigureAwait(false);
}
#endregion

Expand Down
6 changes: 3 additions & 3 deletions NewLife.Core/Data/IPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,12 @@ public static async Task CopyToAsync(this IPacket pk, Stream stream, Cancellatio
for (var p = pk; p != null; p = p.Next)
{
#if NETCOREAPP || NETSTANDARD2_1_OR_GREATER
await stream.WriteAsync(p.GetMemory(), cancellationToken);
await stream.WriteAsync(p.GetMemory(), cancellationToken).ConfigureAwait(false);
#else
if (p is ArrayPacket ap)
await stream.WriteAsync(ap.Buffer, ap.Offset, ap.Length, cancellationToken);
await stream.WriteAsync(ap.Buffer, ap.Offset, ap.Length, cancellationToken).ConfigureAwait(false);
else
await stream.WriteAsync(p.GetMemory(), cancellationToken);
await stream.WriteAsync(p.GetMemory(), cancellationToken).ConfigureAwait(false);
#endif
}
}
Expand Down
8 changes: 4 additions & 4 deletions NewLife.Core/Data/Packet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -425,8 +425,8 @@ public void WriteTo(Byte[] buffer, Int32 offset = 0, Int32 count = -1)
/// <returns></returns>
public async Task CopyToAsync(Stream stream)
{
await stream.WriteAsync(Data, Offset, Count);
if (Next != null) await Next.CopyToAsync(stream);
await stream.WriteAsync(Data, Offset, Count).ConfigureAwait(false);
if (Next != null) await Next.CopyToAsync(stream).ConfigureAwait(false);
}

/// <summary>异步复制到目标数据流</summary>
Expand All @@ -435,8 +435,8 @@ public async Task CopyToAsync(Stream stream)
/// <returns></returns>
public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
{
await stream.WriteAsync(Data, Offset, Count, cancellationToken);
if (Next != null) await Next.CopyToAsync(stream, cancellationToken);
await stream.WriteAsync(Data, Offset, Count, cancellationToken).ConfigureAwait(false);
if (Next != null) await Next.CopyToAsync(stream, cancellationToken).ConfigureAwait(false);
}

/// <summary>深度克隆一份数据包,拷贝数据区</summary>
Expand Down
40 changes: 20 additions & 20 deletions NewLife.Core/Http/HttpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ static async ValueTask<Stream> ConnectCallback(SocketsHttpConnectionContext cont
var addrs = NetUri.ParseAddress(ep.Host);
span?.AppendTag($"addrs={addrs?.Join()}");
if (addrs != null && addrs.Length > 0)
await socket.ConnectAsync(addrs, ep.Port, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
await socket.ConnectAsync(addrs, ep.Port, cancellationToken).ConfigureAwait(false);
else
await socket.ConnectAsync(ep, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
await socket.ConnectAsync(ep, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -529,14 +529,14 @@ private static async Task<String> PostAsync(HttpClient client, String requestUri
{
if (filter != null) await filter.OnRequest(client, request, null, cancellationToken);

var response = await client.SendAsync(request, cancellationToken);
var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);

if (filter != null) await filter.OnResponse(client, response, request, cancellationToken);

#if NET5_0_OR_GREATER
var result = await response.Content.ReadAsStringAsync(cancellationToken);
var result = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
var result = await response.Content.ReadAsStringAsync();
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif

// 增加埋点数据
Expand Down Expand Up @@ -577,11 +577,11 @@ private static HttpClient AddHeaders(this HttpClient client, IDictionary<String,
/// <param name="fileName">目标文件名</param>
public static async Task DownloadFileAsync(this HttpClient client, String requestUri, String fileName)
{
var rs = await client.GetStreamAsync(requestUri);
var rs = await client.GetStreamAsync(requestUri).ConfigureAwait(false);
fileName.EnsureDirectory(true);
using var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
await rs.CopyToAsync(fs);
await fs.FlushAsync();
await rs.CopyToAsync(fs).ConfigureAwait(false);
await fs.FlushAsync().ConfigureAwait(false);
}

/// <summary>下载文件</summary>
Expand All @@ -592,23 +592,23 @@ public static async Task DownloadFileAsync(this HttpClient client, String reques
public static async Task DownloadFileAsync(this HttpClient client, String requestUri, String fileName, CancellationToken cancellationToken)
{
#if NET5_0_OR_GREATER
var rs = await client.GetStreamAsync(requestUri, cancellationToken);
var rs = await client.GetStreamAsync(requestUri, cancellationToken).ConfigureAwait(false);
fileName.EnsureDirectory(true);
using var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
await rs.CopyToAsync(fs, cancellationToken);
await fs.FlushAsync(cancellationToken);
await rs.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
#elif NETSTANDARD2_1_OR_GREATER || NETCOREAPP
var rs = await client.GetStreamAsync(requestUri);
var rs = await client.GetStreamAsync(requestUri).ConfigureAwait(false);
fileName.EnsureDirectory(true);
using var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
await rs.CopyToAsync(fs, cancellationToken);
await fs.FlushAsync(cancellationToken);
await rs.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
#else
var rs = await client.GetStreamAsync(requestUri);
var rs = await client.GetStreamAsync(requestUri).ConfigureAwait(false);
fileName.EnsureDirectory(true);
using var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
await rs.CopyToAsync(fs, 81920, cancellationToken);
await fs.FlushAsync(cancellationToken);
await rs.CopyToAsync(fs, 81920, cancellationToken).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
#endif
}

Expand Down Expand Up @@ -711,7 +711,7 @@ public static async Task ConsumeAndPushAsync(this System.Net.WebSockets.WebSocke
var buf = onProcess != null ? onProcess(msg) : msg.GetBytes();

if (buf != null && buf.Length > 0)
await socket.SendAsync(new ArraySegment<Byte>(buf), System.Net.WebSockets.WebSocketMessageType.Text, true, token);
await socket.SendAsync(new ArraySegment<Byte>(buf), System.Net.WebSockets.WebSocketMessageType.Text, true, token).ConfigureAwait(false);
}
else
{
Expand Down Expand Up @@ -750,7 +750,7 @@ public static async Task WaitForClose(this System.Net.WebSockets.WebSocket socke
var buf = new Byte[4 * 1024];
while (!source.IsCancellationRequested && socket.State == WebSocketState.Open)
{
var data = await socket.ReceiveAsync(new ArraySegment<Byte>(buf), source.Token);
var data = await socket.ReceiveAsync(new ArraySegment<Byte>(buf), source.Token).ConfigureAwait(false);
if (data.MessageType == System.Net.WebSockets.WebSocketMessageType.Close) break;
if (data.MessageType == System.Net.WebSockets.WebSocketMessageType.Text)
{
Expand All @@ -763,7 +763,7 @@ public static async Task WaitForClose(this System.Net.WebSockets.WebSocket socke
if (!source.IsCancellationRequested) source.Cancel();

if (socket.State == WebSocketState.Open)
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "finish", default);
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "finish", default).ConfigureAwait(false);
}
catch (TaskCanceledException) { }
catch (OperationCanceledException) { }
Expand Down
2 changes: 1 addition & 1 deletion NewLife.Core/Http/TinyHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ protected virtual async Task<IOwnerPacket> SendDataAsync(Uri? uri, IPacket? requ
{
// 使用内存流拼接需要多次接收的数据包,降低逻辑复杂度
var ms = new MemoryStream(res.ContentLength);
await rs.CopyToAsync(ms);
await rs.CopyToAsync(ms).ConfigureAwait(false);

var total = rs.Length;
while (total < res.ContentLength)
Expand Down
8 changes: 4 additions & 4 deletions NewLife.Core/IO/CsvFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,15 @@ public virtual async ValueTask DisposeAsync()
_disposed = true;

// 必须刷新写入器,否则可能丢失一截数据
if (_writer != null) await _writer.FlushAsync();
if (_writer != null) await _writer.FlushAsync().ConfigureAwait(false);

if (!_leaveOpen && _stream != null)
{
_reader.TryDispose();

if (_writer != null) await _writer.DisposeAsync();
if (_writer != null) await _writer.DisposeAsync().ConfigureAwait(false);

await _stream.DisposeAsync();
await _stream.DisposeAsync().ConfigureAwait(false);
}

GC.SuppressFinalize(this);
Expand Down Expand Up @@ -210,7 +210,7 @@ public async Task WriteLineAsync(IEnumerable<Object> line)

var str = BuildLine(line);

await _writer.WriteLineAsync(str);
await _writer.WriteLineAsync(str).ConfigureAwait(false);
}

/// <summary>构建一行</summary>
Expand Down
4 changes: 2 additions & 2 deletions NewLife.Core/Net/NetServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ public virtual async Task<Int32> SendAllAsync(IPacket data)
ts.Add(Task.Run(() => item.Value.Send(data)));
}

await Task.WhenAll(ts);
await Task.WhenAll(ts).ConfigureAwait(false);

return Sessions.Count;
}
Expand All @@ -572,7 +572,7 @@ public virtual async Task<Int32> SendAllAsync(IPacket data, Func<INetSession, Bo
ts.Add(Task.Run(() => item.Value.Send(data)));
}

await Task.WhenAll(ts);
await Task.WhenAll(ts).ConfigureAwait(false);

return Sessions.Count;
}
Expand Down
8 changes: 4 additions & 4 deletions NewLife.Core/Net/SessionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -366,9 +366,9 @@ public Int32 Send(ReadOnlySpan<Byte> data)
var ar = Client.BeginReceive(pk.Buffer, 0, pk.Length, SocketFlags.None, null, Client);
var size = ar.IsCompleted ?
Client.EndReceive(ar) :
await Task.Factory.FromAsync(ar, Client.EndReceive);
await Task.Factory.FromAsync(ar, Client.EndReceive).ConfigureAwait(false);
#else
var size = await Client.ReceiveAsync(pk.GetMemory(), SocketFlags.None, cancellationToken);
var size = await Client.ReceiveAsync(pk.GetMemory(), SocketFlags.None, cancellationToken).ConfigureAwait(false);
#endif
if (span != null) span.Value = size;

Expand Down Expand Up @@ -729,7 +729,7 @@ public virtual async Task<Object> SendMessageAsync(Object message)
var rs = (Int32)(Pipeline.Write(ctx, message) ?? 0);
if (rs < 0) return TaskEx.CompletedTask;

return await source.Task;
return await source.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -769,7 +769,7 @@ public virtual async Task<Object> SendMessageAsync(Object message, CancellationT
// https://stackoverflow.com/questions/14627226/why-is-my-async-await-with-cancellationtokensource-leaking-memory
using (cancellationToken.Register(TrySetCanceled, source))
{
return await source.Task;
return await source.Task.ConfigureAwait(false);
}
}
catch (Exception ex)
Expand Down
2 changes: 1 addition & 1 deletion NewLife.Core/Net/TcpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ protected override Int32 OnSend(ReadOnlySpan<Byte> data)
try
{
var pk = new OwnerPacket(BufferSize);
var size = await ss.ReadAsync(pk.Buffer, 0, pk.Length, cancellationToken);
var size = await ss.ReadAsync(pk.Buffer, 0, pk.Length, cancellationToken).ConfigureAwait(false);
if (span != null) span.Value = size;

return pk.Resize(size);
Expand Down
10 changes: 5 additions & 5 deletions NewLife.Core/Net/UdpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ public virtual async Task<Object> SendMessageAsync(Object message)
var rs = (Int32)(Pipeline.Write(ctx, message) ?? -1);
if (rs < 0) return TaskEx.CompletedTask;

return await source.Task;
return await source.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -259,7 +259,7 @@ public virtual async Task<Object> SendMessageAsync(Object message, CancellationT
// 注册取消时的处理,如果没有收到响应,取消发送等待
using (cancellationToken.Register(TrySetCanceled, source))
{
return await source.Task;
return await source.Task.ConfigureAwait(false);
}
}
catch (Exception ex)
Expand Down Expand Up @@ -321,12 +321,12 @@ public IOwnerPacket Receive()
var ar = socket.BeginReceiveFrom(pk.Buffer, 0, pk.Length, SocketFlags.None, ref ep, null, socket);
var size = ar.IsCompleted ?
socket.EndReceive(ar) :
await Task.Factory.FromAsync(ar, e => socket.EndReceiveFrom(e, ref ep));
await Task.Factory.FromAsync(ar, e => socket.EndReceiveFrom(e, ref ep)).ConfigureAwait(false);
#elif NET7_0_OR_GREATER
var result = await socket.ReceiveFromAsync(pk.GetMemory(), ep, cancellationToken);
var result = await socket.ReceiveFromAsync(pk.GetMemory(), ep, cancellationToken).ConfigureAwait(false);
var size = result.ReceivedBytes;
#else
var result = await socket.ReceiveFromAsync(pk.Buffer, SocketFlags.None, ep);
var result = await socket.ReceiveFromAsync(pk.Buffer, SocketFlags.None, ep).ConfigureAwait(false);
var size = result.ReceivedBytes;
#endif
if (span != null) span.Value = size;
Expand Down
4 changes: 2 additions & 2 deletions NewLife.Core/Remoting/ApiHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public static class ApiHelper
// 发起请求
if (filter != null) await filter.OnRequest(client, request, null, cancellationToken);

var response = await client.SendAsync(request, cancellationToken);
var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);

if (filter != null) await filter.OnResponse(client, response, request, cancellationToken);

Expand Down Expand Up @@ -241,7 +241,7 @@ public static HttpContent BuildContent(IPacket pk)
var rtype = typeof(TResult);
if (rtype == typeof(HttpResponseMessage)) return (TResult)(Object)response;

var buf = response.Content == null ? null : (await response.Content.ReadAsByteArrayAsync());
var buf = response.Content == null ? null : (await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false));

// 异常处理
if (response.StatusCode >= HttpStatusCode.BadRequest)
Expand Down
2 changes: 1 addition & 1 deletion NewLife.Core/Remoting/ApiHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ protected virtual async Task<HttpResponseMessage> SendOnServiceAsync(HttpRequest
var filter = Filter;
if (filter != null) await filter.OnRequest(client, request, this, cancellationToken);

var response = await client.SendAsync(request, cancellationToken);
var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);

if (filter != null) await filter.OnResponse(client, response, this, cancellationToken);

Expand Down
Loading

0 comments on commit aba0005

Please sign in to comment.