Click here to Skip to main content
15,897,187 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 93.2K   1.4K   137  
Using SynchronizationContext with WCF.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace StaThreadSyncronizer
{
   internal class StaThread
   {
      private Thread mStaThread;
      private IQueueReader<SendOrPostCallbackItem> mQueueConsumer;
      private int mThreadID;
      private ManualResetEvent mStopEvent = new ManualResetEvent(false);


      internal StaThread(IQueueReader<SendOrPostCallbackItem> reader)
      {
         mQueueConsumer = reader;
         mStaThread = new Thread(Run);
         mStaThread.Name = "STA Worker Thread";
         mStaThread.SetApartmentState(ApartmentState.STA);
      }

      internal int ManagedThreadId
      {
         get
         {
            return mThreadID;
         }
      }
      

      internal void Start()
      {
         mStaThread.Start();
      }


      internal void Join()
      {
         mStaThread.Join();
      }

      private void Run()
      {
         mThreadID = Thread.CurrentThread.ManagedThreadId;
         while (true)
         {
            bool stop = mStopEvent.WaitOne(0);
            if (stop)
            {
               break;
            }

           SendOrPostCallbackItem workItem = mQueueConsumer.Dequeue();
           if (workItem != null)
               workItem.Execute();
         }
      }

      internal void Stop()
      {
         mStopEvent.Set();
         mQueueConsumer.ReleaseReader();
         mStaThread.Join();
         mQueueConsumer.Dispose();         
      }
   }
}

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