0

我有一个客户端和一个服务器应用程序,并希望通过命名管道将序列化的小对象从客户端发送到服务器。除了第一次传输之外,它运行良好:每次启动应用程序后最多需要两秒钟。以下转移几乎是即时的。

这是我的服务器代码:

class PipeServer
{
    public static string PipeName = @"OrderPipe";
    public static async Task<Order> Listen()
    {
        using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
        {
            await Task.Factory.FromAsync(pipeServer.BeginWaitForConnection, pipeServer.EndWaitForConnection, null);

            using (StreamReader reader = new StreamReader(pipeServer))
            {
                string text = await reader.ReadToEndAsync();
                var order =  JsonConvert.DeserializeObject<Order>(text);
                Console.WriteLine(DateTime.Now + ": Order recieved from Client: " + order.Zertifikat.Wkn + " with price " + order.PriceItem.Price + " with time " + order.PriceItem.Time);
                return order;
            }
        }
    }
}

这是客户:

class PipeClient
{
    public static string PipeName = @"OrderPipe";

    private static async Task SendAwait(Order order, int timeOut = 10)
    {
        using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous))
        {
            pipeStream.Connect(timeOut);
            Console.WriteLine(DateTime.Now + ": Pipe connection to Trader established.");

            using (StreamWriter sw = new StreamWriter(pipeStream))
            {
                string orderSerialized = JsonConvert.SerializeObject(order);
                await sw.WriteAsync(orderSerialized);
                Console.WriteLine(DateTime.Now + ": Order sent.");
                // flush
                await pipeStream.FlushAsync();
            }
        }
    }

    public static async void SendOrder(Order order)
    {
        try
        {
            await SendAwait(order);
        }
        catch (TimeoutException)
        {
            Console.WriteLine("Order was not sent because Server could not be reached.");
        }
        catch (IOException e)
        {
            Console.WriteLine("Order was not sent because an Exception occured: " + e.Message);
        }
    }
}

正在传输的数据是一种对时间高度敏感的证券交易所订单,所以对我来说,第一笔订单也必须毫不拖延地工作。

有没有其他方法可以使命名管道的第一次使用与其他命名管道一样快?某种预编译?

我真的想避免额外的线程检查是否可以建立连接并每 x 秒发送一次虚拟数据只是为了“预热”导致延迟的相应对象。

(顺便说一句:代码不是我的,我是从这里得到的!)

4

0 回答 0