// ---------------------------------------------------------------------------- // To compile: // csc -debug+ -r:System.ServiceModel.dll AsyncClientSample.cs // // This sample is provided "AS IS" with no warranties, and confers no rights. // // Sample output: // C:\>AsyncClientSample // Done starting asynchronous operations. // Hello(A) taking a long time... // Hello(B) taking a long time... // Hello(C) taking a long time... // Hello(A) returning "A was number 1" // A was number 1 // Hello(B) returning "B was number 2" // B was number 2 // Hello(C) returning "C was number 3" // C was number 3 // using System; using System.ServiceModel; using System.Threading; class App { public static void Main() { Binding binding = new NetProfileTcpBinding(); Uri uri = new Uri("net.tcp://localhost/AsyncClientSample"); using (ServiceHost host = new ServiceHost()) { host.AddEndpoint(typeof(ISyncHello), binding, uri); host.Open(); using (IHelloChannel channel = ChannelFactory.CreateChannel(uri, binding)) { IAsyncResult a = channel.BeginHello("A", null, null); IAsyncResult b = channel.BeginHello("B", null, null); IAsyncResult c = channel.BeginHello("C", null, null); Console.WriteLine("Done starting asynchronous operations."); Console.WriteLine("{0}", channel.EndHello(a)); Console.WriteLine("{0}", channel.EndHello(b)); Console.WriteLine("{0}", channel.EndHello(c)); channel.Close(); } host.Close(); } } } // ---------------------------------------------------------------------------- interface IHelloChannel : IAsyncHello, IProxyChannel { } [ServiceContract(Name="Hello")] interface IAsyncHello { [OperationContract(AsyncPattern=true)] IAsyncResult BeginHello(string greeting, AsyncCallback callback, object state); string EndHello(IAsyncResult result); } [ServiceContract(Name="Hello")] interface ISyncHello { [OperationContract] string Hello(string greeting); } [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple)] class HelloService : ISyncHello { static int id; public string Hello(string greeting) { Console.WriteLine("Hello({0}) taking a long time...", greeting); Thread.Sleep(5000); string result = String.Format("{0} was number {1}", greeting, Interlocked.Increment(ref id)); Console.WriteLine("Hello({0}) returning \"{1}\"", greeting, result); return result; } }