Blog Archive

Monday, July 30, 2012

Implement Asyn WCF using Task in .Net 4.0

In Fx 4.5 Task can be returned but in Fx 4.0, task can only be on Server:

    public interface IService1
    {
        [OperationContract(AsyncPattern=true)]
        IAsyncResult BeginGetDataAsync(int value, AsyncCallback cb, object state);

         string EndGetDataAsync(IAsyncResult ar);
    }

         string GetData(int value)
        {
            Random r = new Random();
            Thread.Sleep(TimeSpan.FromSeconds(3));
            return r.NextDouble().ToString();
        }

        public IAsyncResult BeginGetDataAsync(int value, AsyncCallback cb, object state)
        {
            var t = Task<string>.Factory.StartNew((s) => { return GetData(value); },state);  // must pass state into Lambda
            return t.ContinueWith(res => cb(t));

        }

        public string EndGetDataAsync(IAsyncResult ar)
        {
            return ((Task<string>)ar).Result;
        }


Client --- need to add Servicew Ref with support of async WCF checked

            object state = "";
            ServiceReference1.Service1Client c = new ServiceReference1.Service1Client();
           

            int NUM = 10;

            Stopwatch sw= new Stopwatch();
            sw.Start();

            Parallel.For(0, NUM, (ls) =>
                {
                    //for (int i = 0; i < NUM; i++)
                    //{
                    var t = Task<string>.Factory.FromAsync(c.BeginGetDataAsync, c.EndGetDataAsync, 10, state);
                    string s = t.Result;
                    Console.WriteLine(s);
                    //}
                });

     
            c.Close();
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();

No comments: