How to avoid creating new byte arrays for each invocation of a WCF operation method?
Is there a way to avoid creating new byte array instances with fixed lengths and calling Array.Copy
from the larger byte array Buffer
to the newly created reply array called reply
?
- Change the API of the WCF Host!?
- Use a to-me-unbeknownst method that creates an Array-looking-&-behaving view onto another array?
Or any other ideas?
// Buffer : byte[]
// host : a WCF host
while (code >= 0)
{
try
{
if (Socket.Available == 0)
{
Thread.Sleep(Wait);
continue;
}
var length = Socket.Receive(Buffer);
if (length > 0)
{
Log("Read", ServerPort, " ->", Client, length);
开发者_开发知识库 var reply = new byte[length];
Array.Copy(Buffer, reply, length);
try { code = host.Reply(ServerPort, Client, reply); }
catch (Exception ex)
{
code = -2;
Log("Exception", ServerPort, "<=>", Client, ex);
ConnectToHost();
}
}
}
catch (Exception ex)
{
code = -3;
Delist();
if (ex.GetType() != typeof(ThreadAbortException))
Log("Exception", ServerPort, "!!!", Client, ex);
Log("Disconnect", ServerPort, @"<\>", Client, Relay.Host.Address());
Tcp.Close();
}
You can use ArraySegment<T> as a way to pass around pieces of a larger byte array. I think the API is kinda crappy, but it certainly does the trick.
However, seems like you'd probably also benefit from using the BufferManager class provided for WCF for managing reusable buffers in your code.
精彩评论