Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C#

Understanding SynchronizationContext: Part III

Rate me:
Please Sign up or sign in to vote.
4.96/5 (47 votes)
29 Dec 2008CPOL10 min read 93K   1.4K   137  
Using SynchronizationContext with WCF.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;

namespace StaThreadSyncronizer
{
   internal interface IItemQueue : IDisposable
   {
      bool IsEmpty { get; }
      SendOrPostCallbackItem Dequeue();
   }

   internal class SyncronizationQueue : IItemQueue, IDisposable
   {
      private Queue<SendOrPostCallbackItem> mQueue;
      private object mSync = new object();
      private AutoResetEvent mItemsInQueueEvent = new AutoResetEvent(false);

      public SyncronizationQueue()
      {
         mQueue = new Queue<SendOrPostCallbackItem>();
      }

      public void AddItem(SendOrPostCallbackItem item)
      {
         lock (((ICollection)mQueue).SyncRoot)
         {            
            mQueue.Enqueue(item);
            mItemsInQueueEvent.Set();
         }
      }

      public void Dispose()
      {
         lock (((ICollection)mQueue).SyncRoot)
         {
            // release any lock 
            mItemsInQueueEvent.Set();
            mQueue.Clear();            
         }
         

      }

      public bool IsEmpty
      {
         get
         {
            lock (mSync)
            {
               return mQueue.Count == 0;
            }
         }
      }

      public SendOrPostCallbackItem Dequeue()
      {
         Console.WriteLine("Before " + mQueue.Count);
         mItemsInQueueEvent.WaitOne();
         Console.WriteLine("After");
         SendOrPostCallbackItem item = null;
         lock (((ICollection)mQueue).SyncRoot)
         {
           if (mQueue.Count > 0)
             item = mQueue.Dequeue();
         }
         

         return item;
      }
   }
}

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
I am currently working as a team leader with a group of amazing .NET programmers. I love coding with .NET, and I love to apply design patterns into my work. Lately I had some free time, so I decided to write some articles, hoping I will spare someone frustration and anxiety.

Comments and Discussions