命名管道:启动应用程序后的第一次数据传输非常慢

时间:2016-10-30 14:34:45

标签: c# named-pipes namedpipeserverstream precompiling

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

这是我的服务器代码:

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秒发送一次虚拟数据只是为了#34;预热&#34;导致延迟的各个对象。

(顺便说一下:代码不是来自我,我是从here得到的!)

0 个答案:

没有答案