Skip to content

Commit 0d36dfb

Browse files
committed
Defer creation of lambda in WritePacketAsync.
1 parent cddc2d8 commit 0d36dfb

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/MySqlConnector/Protocol/Serialization/ProtocolUtility.cs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77

88
namespace MySql.Data.Protocol.Serialization
99
{
10-
internal static class ProtocolUtility
11-
{
10+
internal static class ProtocolUtility
11+
{
1212
public static ValueTask<Packet> ReadPacketAsync(BufferedByteReader bufferedByteReader, IByteHandler byteHandler, Func<int> getNextSequenceNumber, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior)
1313
{
1414
var headerBytesTask = bufferedByteReader.ReadBytesAsync(byteHandler, 4, ioBehavior);
@@ -135,14 +135,25 @@ public static ValueTask<int> WritePacketAsync(IByteHandler byteHandler, int sequ
135135
SerializationUtility.WriteUInt32((uint) contents.Count, buffer, 0, 3);
136136
buffer[3] = (byte) sequenceNumber;
137137
Buffer.BlockCopy(contents.Array, contents.Offset, buffer, 4, contents.Count);
138-
return byteHandler.WriteBytesAsync(new ArraySegment<byte>(buffer, 0, bufferLength), ioBehavior)
139-
.ContinueWith(x =>
138+
var task = byteHandler.WriteBytesAsync(new ArraySegment<byte>(buffer, 0, bufferLength), ioBehavior);
139+
if (task.IsCompletedSuccessfully)
140+
{
141+
ArrayPool<byte>.Shared.Return(buffer);
142+
return default(ValueTask<int>);
143+
}
144+
return AddContinuation(task, buffer);
145+
146+
// NOTE: use a local function (with no captures) to defer creation of lambda objects
147+
ValueTask<int> AddContinuation(ValueTask<int> task_, byte[] buffer_)
148+
{
149+
return task_.ContinueWith(x =>
140150
{
141-
ArrayPool<byte>.Shared.Return(buffer);
151+
ArrayPool<byte>.Shared.Return(buffer_);
142152
return default(ValueTask<int>);
143153
});
154+
}
144155
}
145156

146-
public const int MaxPacketSize = 16777215;
147-
}
157+
public const int MaxPacketSize = 16777215;
158+
}
148159
}

0 commit comments

Comments
 (0)