項目中使用的wcf服務調用起來反映比較慢,昨天看了下怎么使用tcp協議傳輸,今天就對tcp和http的調用效率做了一個比較。
一.寄宿與iis的tcp協議的服務調用和控制台自寄宿http協議的服務調用的比較:
因為tcp協議不能使用控制台自寄宿,所以用iis來代替,http使用輕量級的自寄宿。
客戶端的調用:
static void Main(string[] args) { //比較一下使用http和tcp的性能 TestHttpService(); TestTcpService(); Console.Read(); } private static void TestTcpService() { using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("calculatorservice")) { ICalculator calculator = channelFactory.CreateChannel(); using (calculator as IDisposable) { try { DateTime beginTime = DateTime.Now; calculator.Add(1, 2); DateTime endTime = DateTime.Now; Console.WriteLine("tcp調用花費時間:" + (endTime-beginTime).TotalMilliseconds.ToString()); } catch (CommunicationException) { (calculator as ICommunicationObject).Abort(); throw; } catch (TimeoutException) { (calculator as ICommunicationObject).Abort(); throw; } } } } private static void TestHttpService() { using (HttpService.CalculatorClient client = new HttpService.CalculatorClient()) { try { DateTime beginTime = DateTime.Now; client.Add(1, 2); DateTime endTime = DateTime.Now; Console.WriteLine("http調用花費時間:" + (endTime - beginTime).TotalMilliseconds.ToString()); } catch (CommunicationException) { (client as ICommunicationObject).Abort(); throw; } catch (TimeoutException) { (client as ICommunicationObject).Abort(); throw; } } }
控制台自寄宿的實現:
static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(CalculatorService))) { host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://127.0.0.1:9999/calculatorservice"); if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri("http://127.0.0.1:9999/calculatorservice/metadata"); host.Description.Behaviors.Add(behavior); } host.Opened += delegate { Console.WriteLine("CalculaorService已經啟動,按任意鍵終止服務!"); }; host.Open(); Console.Read(); } }
wcf的調用,使用毫秒級的單位就可以體現出來區別了,運行自寄宿程序,啟動iis,第一次調用的速度真是坑,tcp的調用也用了800毫秒,而http竟然用了6秒多:
第二次運行速度就快了很多,不過http還是比較慢:
二.wcf應用程序的http協議和控制台寄宿的http協議的效率比較:
第一次調用:
第二次調用,vs調試器的效率竟然基本沒有變化,被自寄宿的給爆成渣了:
應該比較一下iis寄宿的http協議的效率,不過老是報錯,今天就先到這里,過兩天補上,未完待續...