Click here to Skip to main content
15,896,154 members
Articles / Programming Languages / C#

WCF Cache

Rate me:
Please Sign up or sign in to vote.
4.69/5 (16 votes)
9 Dec 2009CPOL4 min read 105.1K   4.1K   44  
A WCF Service caching example.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WCFClient.AdventureWorks;
using System.Threading;
using System.Collections;

namespace WCFClient
{
    public partial class FmMain : Form
    {
        private ManualResetEvent _stopThread = new ManualResetEvent(false);
        private ArrayList _executionResults;
        private List<Thread> _threadList = new List<Thread>();
        private DateTime? startTime;
        private bool _threadsStarted = false;

        public FmMain()
        {
            InitializeComponent();
            _executionResults = ArrayList.Synchronized(new ArrayList());
        }

        private void Log(string message)
        {
            object[] pList = { this,  new UpdateLogEventArgs(message)};
            lbLog.BeginInvoke(new System.EventHandler(UpdateLogs), pList);
        }

        private void UpdateLogs(object o, System.EventArgs e)
        {
            lbLog.Items.Insert(0, ((UpdateLogEventArgs)e).Message);
            while (lbLog.Items.Count > 1000)
            {
                lbLog.Items.RemoveAt(lbLog.Items.Count - 1);
            }
        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            if (_threadsStarted)
            {
                MessageBox.Show("Stop threads first.");
                return;
            }

            _threadsStarted = true;

            _stopThread.Reset();

            startTime = DateTime.Now;
            
            int threadNumber = 10;
            if (!int.TryParse(mtbThreadNumber.Text, out threadNumber))
            {
                MessageBox.Show("Please specify a valid thread number.");
                return;
            }
            Log("Getting product IDs...");

            List<int> productIDs = new List<int>();

            try
            {
                using (ProductsServiceClient client = new ProductsServiceClient())
                {
                    productIDs = new List<int>(client.GetProductIDList());
                }
            }
            catch (Exception ex)
            {
                Log("Error: " + ex.Message);
                Log("Process stopped.");
                return;
            }

            Log(string.Format("Starting Threads...... Thread Number: {0}", threadNumber));

            for (int i = 0; i < threadNumber; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(DoGetProducts));
                _threadList.Add(t);
                t.Start(new ThreadInput() { ThreadIndex = i, IDList = productIDs });
            }
        }

        private void DoGetProducts(object threadInputObj)
        {
            try
            {
                ThreadInput threadInput = (ThreadInput)threadInputObj;
                List<int> idList = (List<int>)threadInput.IDList;
                Random rNextIndex = new Random(threadInput.ThreadIndex);
                Random rNextTimeout = new Random(threadInput.ThreadIndex);
                using (ProductsServiceClient client = new ProductsServiceClient())
                {
                    while (true)
                    {
                        int nextIndex = rNextIndex.Next(idList.Count);
                        Log(string.Format("Getting product. ID = {0}", idList[nextIndex]));
                        DateTime start = DateTime.Now;                    
                        Product p = client.GetProduct(idList[nextIndex]);
                        if (p != null)
                        {
                            DateTime end = DateTime.Now;
                            lock (_executionResults.SyncRoot)
                            {
                                _executionResults.Add(end.Subtract(start).TotalMilliseconds);
                            }
                            Log(string.Format("Got product. Product Number: {0}", p.ProductNumber));
                        }                       
                        
                        //this is for making the load oscillating
                        Thread.Sleep(rNextTimeout.Next(1000));
                        if (_stopThread.WaitOne(0, false))
                        {
                            Log("Thread Stopped.");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log("Error in the theread: " + ex.Message);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            startTime = null;
            _stopThread.Set();
            
            Thread.Sleep(2000);
            
            foreach (Thread thread in _threadList)
            {
                if (thread.ThreadState != ThreadState.Stopped)
                {
                    thread.Abort();
                }
            }
            
            Refresh();
            double totalSum = 0;
            lock (_executionResults.SyncRoot)
            {
                if (_executionResults.Count > 0)
                {
                    Log("Calculating results....");
                    foreach (double et in _executionResults)
                    {
                        totalSum += et;
                    }

                    int averageCallTime = (int)(totalSum / (double)_executionResults.Count);
                    Log(string.Format("Average call time is {0} milliseconds. Total number of calls was {1}", averageCallTime, _executionResults.Count));
                    _executionResults.Clear();
                }
                else
                {
                    Log("There are no result.");
                }
            }

            _threadsStarted = false;
        }

        private void tWorkingTime_Tick(object sender, EventArgs e)
        {
            if (startTime != null)
            {
                DateTime now = DateTime.Now;
                lblWorkingTime.Text = string.Format("{0:00}:{1:00}", now.Subtract(startTime.GetValueOrDefault()).Minutes, now.Subtract(startTime.GetValueOrDefault()).Seconds);
            }
        }

        private void FmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_threadsStarted)
            {
                btnStop_Click(null, null);
            }
        }
    }

    public class UpdateLogEventArgs : EventArgs
    {
        private string _message;

        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }

        public UpdateLogEventArgs(string message)
        {
            this._message = message;
        }
    }

    public class ThreadInput
    {
        public List<int> IDList;
        public int ThreadIndex;
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions