<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-9202309254227413537</id><updated>2012-02-16T09:03:10.265-08:00</updated><category term='Extended Methods'/><category term='Threading'/><category term='EndInvoke'/><category term='Template'/><category term='IE6'/><category term='Spring.net'/><category term='Thread'/><category term='Bug'/><category term='Silverlight dmvm dm-v-vm'/><category term='MVP'/><category term='UI'/><category term='C# .net compoiste design patterns'/><category term='SyncrhronizationContext'/><category term='DI'/><category term='C++'/><category term='C#'/><category term='Friend'/><category term='Reflection'/><category term='Singleton'/><category term='Nunit'/><category term='BeginInvoke'/><category term='enum reflection .net C# attributes'/><category term='Depndency Injection'/><category term='Asynchronous Method Invocation Thread UI Invoke BeginInvoke Control'/><category term='.NET'/><category term='Silverlight'/><title type='text'>Peretz.Net</title><subtitle type='html'>Fun stuff with .NET and C#</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>31</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-9221275004653872966</id><published>2011-04-16T17:48:00.001-07:00</published><updated>2011-04-16T17:48:55.209-07:00</updated><title type='text'></title><content type='html'>&lt;h1&gt;How to turn off your monitor&lt;/h1&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;namespace TurnoffMonitor&lt;br /&gt;{&lt;br /&gt;    /// &lt;summary&gt;&lt;br /&gt;    /// Interaction logic for MainWindow.xaml&lt;br /&gt;    /// &lt;/summary&gt;&lt;br /&gt;    public partial class MainWindow : Window&lt;br /&gt;    {&lt;br /&gt;        [DllImport("user32.dll")]&lt;br /&gt;        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg,&lt;br /&gt;                      IntPtr wParam, IntPtr lParam);&lt;br /&gt;&lt;br /&gt;        const int SC_MONITORPOWER = 0xF170;&lt;br /&gt;        const uint WM_SYSCOMMAND = 0x0112;&lt;br /&gt;        &lt;br /&gt;        const int MONITOR_ON = -1;&lt;br /&gt;        const int MONITOR_OFF = 2;&lt;br /&gt;        const int MONITOR_STANBY = 1;&lt;br /&gt;        &lt;br /&gt;        public MainWindow()&lt;br /&gt;        {&lt;br /&gt;            InitializeComponent();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void ExecuteButton_Click(object sender, RoutedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            WindowInteropHelper helper = new WindowInteropHelper(this);&lt;br /&gt;            var handle = helper.Handle;&lt;br /&gt;&lt;br /&gt;            &lt;br /&gt;            SendMessage(handle, WM_SYSCOMMAND, new IntPtr(SC_MONITORPOWER), new IntPtr(MONITOR_OFF));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-9221275004653872966?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/9221275004653872966/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=9221275004653872966' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/9221275004653872966'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/9221275004653872966'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2011/04/how-to-turn-off-your-monitor-namespace.html' title=''/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-3777265368189063003</id><published>2010-04-10T13:15:00.000-07:00</published><updated>2010-04-10T22:23:11.173-07:00</updated><title type='text'>WCF 4.0 Service Discovery - Adding the binding to the discovery</title><content type='html'>With WCF 4.0 a wonderful new feature is added. Service Discovery allows us to see what services are running and where they are. However, when I started to look into this in detail, I noticed the information you get on services only contains the A (Address) and C (Contract) of the ABC, The Address and the Contract - but not the binding. So in this article I will show how to add the binding to the discovery information with little ease.&lt;br /&gt;&lt;br /&gt;Note: All the code is developed on Visual Studio 2010 RC&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;EndpointDiscoveryMetadata&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;Within the discovery this class is probably one of the most important ones. This is the information we get when services go up and down. Below you can see that there is no binding information about the service.&lt;br /&gt;&lt;br /&gt;Notice you can get the contact names, using:&lt;br /&gt;&lt;code&gt;Collection&lt;xmlqualifiedname&gt; ContractTypeNames { get; }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;and you can get the address using:&lt;br /&gt;&lt;code&gt;public EndpointAddress Address { get; set; }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;But, no binding information!&lt;br /&gt;&lt;br /&gt;When I posted on the forum asking why was it done this way, they told me that the binding are not part of the discovery standard (WS Discovery), they also told me that you can get the binding without problems by simply discovering the Mex endpoint and then issuing a call to get the metadata of the service. But, that is not ideal, you would need to discovery the service, and then get its metadata just to know the full ABC of an endpoint (2 network trips).&lt;br /&gt;(http://social.msdn.microsoft.com/Forums/en/wcfprerelease/thread/ca6bc4be-bc46-4740-ba1e-dca8cf39aa5f)&lt;br /&gt;&lt;br /&gt;One key field that EndpointDiscoveryMetadata has is Extensions. So right away I decided to see how I can fill up these extensions and add my own custom information in there. In this case it would be binding information.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;The code&lt;/h2&gt;&lt;br /&gt;The example below is based on the WCF / WF code examples from Microsoft. The code has been modified to add binding information to the discovery metadata. I have used the Service Proxy example for this prototype.&lt;br /&gt;&lt;br /&gt;You can get the Microsoft sample code here: &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=35ec8682-d5fd-4bc3-a51a-d8ad115a8792&amp;amp;displaylang=en"&gt;http://www.microsoft.com/downloads/details.aspx?FamilyID=35ec8682-d5fd-4bc3-a51a-d8ad115a8792&amp;amp;displaylang=en&lt;/a&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;h2&gt;Adding Extensions to the EndpointDiscoveryMetadata&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;To add an extension to the Discovery Metadata, you need to create a new Endpoint Behavior and add it to the &lt;code&gt;Endpoint.Behaviors&lt;/code&gt; collection. The behavior is a special behavior that belongs to the Discovery sub-system, it is called &lt;code&gt;EndpointDiscoveryBehavior&lt;/code&gt;. Once you create this behavior you can add extensions to it using the Extension collection.&lt;br /&gt;&lt;code&gt;endpointDiscoveryBehavior.Extensions.Add&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;To make sure that the binding information is attached to the discovery metadata of each endpoint, the best approach was to create a new ServiceBehavior, and add a &lt;code&gt;EndpointDiscoveryBehavior&lt;/code&gt; to each endpoint.&lt;br /&gt;&lt;br /&gt;Below is the code of the Service Behavior:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    public class BindingDiscoveryServiceBehavior : Attribute, IServiceBehavior&lt;br /&gt;    {&lt;br /&gt;        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection&lt;ServiceEndpoint&gt; endpoints, BindingParameterCollection bindingParameters)&lt;br /&gt;        {&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)&lt;br /&gt;        {&lt;br /&gt;            var endpoints = serviceDescription.Endpoints;&lt;br /&gt;&lt;br /&gt;            foreach (ServiceEndpoint endpoint in endpoints)&lt;br /&gt;            {&lt;br /&gt;                var endpointDiscoveryBehavior = new EndpointDiscoveryBehavior();&lt;br /&gt;&lt;br /&gt;                StringBuilder sb = new StringBuilder();&lt;br /&gt;&lt;br /&gt;                sb.Append(endpoint.Address); &lt;br /&gt;                sb.Append(Environment.NewLine);&lt;br /&gt;                sb.Append(endpoint.Binding.Scheme);&lt;br /&gt;                sb.Append(Environment.NewLine);&lt;br /&gt;                sb.Append(endpoint.Binding.Name);&lt;br /&gt;&lt;br /&gt;                string bindingInfo = sb.ToString();&lt;br /&gt;                string largeData = String.Empty;&lt;br /&gt;&lt;br /&gt;                StringBuilder sb2 = new StringBuilder();&lt;br /&gt;                for (int i = 0; i &lt; 3000000; i++)&lt;br /&gt;                    sb2.Append("Lots of data " + i.ToString() + Environment.NewLine);&lt;br /&gt;&lt;br /&gt;                largeData = sb2.ToString();&lt;br /&gt;&lt;br /&gt;                // add the binding information to the endpoint&lt;br /&gt;                endpointDiscoveryBehavior.Extensions.Add(&lt;br /&gt;                    new XElement(&lt;br /&gt;                        "root",&lt;br /&gt;                        new XElement("BindingData", bindingInfo),&lt;br /&gt;                        new XElement("LargeData", largeData)));&lt;br /&gt;&lt;br /&gt;                // add the extension&lt;br /&gt;                endpoint.Behaviors.Add(endpointDiscoveryBehavior);&lt;br /&gt;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)&lt;br /&gt;        {&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Note that I have also added a very large data to the extension, just to show that you can pass large amount of data in the Extensions. (but you need to increase the limits on the discovery proxy TCP binding).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The next step is simple, you just need to add your Service Behavior to your service. You can do this by configuration, or simply applying it as an attribute on the service:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;[BindingDiscoveryServiceBehavior]&lt;br /&gt;public class CalculatorService : ICalculatorService&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Getting the information when a service is "Discovered"&lt;/h2&gt;&lt;br /&gt;To see the binding information when a service is discovered, I have modified the Service Proxy from the WCF discovery example:&lt;br /&gt;&lt;br /&gt;When a service is discovered, the &lt;code&gt;OnBeginOnlineAnnouncement&lt;/code&gt; is called..&lt;br /&gt;&lt;br /&gt;Below is the modified implementation:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]&lt;br /&gt;    public class DiscoveryProxyService : DiscoveryProxy&lt;br /&gt;    {&lt;br /&gt;        // Repository to store EndpointDiscoveryMetadata. A database or a flat file could also be used instead.&lt;br /&gt;        Dictionary&lt;EndpointAddress, EndpointDiscoveryMetadata&gt; onlineServices;&lt;br /&gt;&lt;br /&gt;        public DiscoveryProxyService()&lt;br /&gt;        {&lt;br /&gt;            this.onlineServices = new Dictionary&lt;EndpointAddress, EndpointDiscoveryMetadata&gt;();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // OnBeginOnlineAnnouncement method is called when a Hello message is received by the Proxy&lt;br /&gt;        protected override IAsyncResult OnBeginOnlineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state)&lt;br /&gt;        {        &lt;br /&gt;            this.AddOnlineService(endpointDiscoveryMetadata);&lt;br /&gt;            return new OnOnlineAnnouncementAsyncResult(callback, state);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override void OnEndOnlineAnnouncement(IAsyncResult result)&lt;br /&gt;        {&lt;br /&gt;            OnOnlineAnnouncementAsyncResult.End(result);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // OnBeginOfflineAnnouncement method is called when a Bye message is received by the Proxy&lt;br /&gt;        protected override IAsyncResult OnBeginOfflineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state)&lt;br /&gt;        {            &lt;br /&gt;            this.RemoveOnlineService(endpointDiscoveryMetadata);&lt;br /&gt;            return new OnOfflineAnnouncementAsyncResult(callback, state);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override void OnEndOfflineAnnouncement(IAsyncResult result)&lt;br /&gt;        {&lt;br /&gt;            OnOfflineAnnouncementAsyncResult.End(result);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // OnBeginFind method is called when a Probe request message is received by the Proxy&lt;br /&gt;        protected override IAsyncResult OnBeginFind(FindRequestContext findRequestContext, AsyncCallback callback, object state)&lt;br /&gt;        {&lt;br /&gt;            this.MatchFromOnlineService(findRequestContext);&lt;br /&gt;            return new OnFindAsyncResult(callback, state);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override void OnEndFind(IAsyncResult result)&lt;br /&gt;        {&lt;br /&gt;            OnFindAsyncResult.End(result);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // OnBeginFind method is called when a Resolve request message is received by the Proxy&lt;br /&gt;        protected override IAsyncResult OnBeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state)&lt;br /&gt;        {&lt;br /&gt;            return new OnResolveAsyncResult(this.MatchFromOnlineService(resolveCriteria), callback, state);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override EndpointDiscoveryMetadata OnEndResolve(IAsyncResult result)&lt;br /&gt;        {&lt;br /&gt;            return OnResolveAsyncResult.End(result);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // The following are helper methods required by the Proxy implementation&lt;br /&gt;        void AddOnlineService(EndpointDiscoveryMetadata endpointDiscoveryMetadata)&lt;br /&gt;        {&lt;br /&gt;            lock (this.onlineServices)&lt;br /&gt;            {&lt;br /&gt;                this.onlineServices[endpointDiscoveryMetadata.Address] = endpointDiscoveryMetadata;                &lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            PrintDiscoveryMetadata(endpointDiscoveryMetadata, "Adding");&lt;br /&gt;            // show the binding information&lt;br /&gt;            PrintBindingInformation(endpointDiscoveryMetadata);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void PrintBindingInformation(EndpointDiscoveryMetadata endpointDiscoveryMetadata)&lt;br /&gt;        {&lt;br /&gt;            // Get the binding data&lt;br /&gt;            XElement element = endpointDiscoveryMetadata.Extensions.Elements("BindingData").FirstOrDefault();&lt;br /&gt;            string bindingInfo = element.Value;&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Binding Data");&lt;br /&gt;            Console.WriteLine(bindingInfo);          &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void RemoveOnlineService(EndpointDiscoveryMetadata endpointDiscoveryMetadata)&lt;br /&gt;        {            &lt;br /&gt;            if (endpointDiscoveryMetadata != null)&lt;br /&gt;            {&lt;br /&gt;                lock (this.onlineServices)&lt;br /&gt;                {&lt;br /&gt;                    this.onlineServices.Remove(endpointDiscoveryMetadata.Address);                    &lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                PrintDiscoveryMetadata(endpointDiscoveryMetadata, "Removing");&lt;br /&gt;            }    &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void MatchFromOnlineService(FindRequestContext findRequestContext)&lt;br /&gt;        {&lt;br /&gt;            lock (this.onlineServices)&lt;br /&gt;            {&lt;br /&gt;                foreach (EndpointDiscoveryMetadata endpointDiscoveryMetadata in this.onlineServices.Values)&lt;br /&gt;                {&lt;br /&gt;                    if (findRequestContext.Criteria.IsMatch(endpointDiscoveryMetadata))&lt;br /&gt;                    {                        &lt;br /&gt;                        findRequestContext.AddMatchingEndpoint(endpointDiscoveryMetadata);&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        EndpointDiscoveryMetadata MatchFromOnlineService(ResolveCriteria criteria)&lt;br /&gt;        {&lt;br /&gt;            EndpointDiscoveryMetadata matchingEndpoint = null;&lt;br /&gt;            lock (this.onlineServices)&lt;br /&gt;            {&lt;br /&gt;                foreach (EndpointDiscoveryMetadata endpointDiscoveryMetadata in this.onlineServices.Values)&lt;br /&gt;                {&lt;br /&gt;                    if (criteria.Address == endpointDiscoveryMetadata.Address)&lt;br /&gt;                    {&lt;br /&gt;                        matchingEndpoint = endpointDiscoveryMetadata;&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            return matchingEndpoint;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void PrintDiscoveryMetadata(EndpointDiscoveryMetadata endpointDiscoveryMetadata, string verb)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine("\n**** " + verb + " service of the following type from cache. ");&lt;br /&gt;            foreach (XmlQualifiedName contractName in endpointDiscoveryMetadata.ContractTypeNames)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine("** " + contractName.ToString());&lt;br /&gt;                break;&lt;br /&gt;            }&lt;br /&gt;            Console.WriteLine("**** Operation Completed");&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        sealed class OnOnlineAnnouncementAsyncResult : AsyncResult&lt;br /&gt;        {&lt;br /&gt;            public OnOnlineAnnouncementAsyncResult(AsyncCallback callback, object state)&lt;br /&gt;                : base(callback, state)&lt;br /&gt;            {&lt;br /&gt;                this.Complete(true);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public static void End(IAsyncResult result)&lt;br /&gt;            {&lt;br /&gt;                AsyncResult.End&lt;OnOnlineAnnouncementAsyncResult&gt;(result);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        sealed class OnOfflineAnnouncementAsyncResult : AsyncResult&lt;br /&gt;        {&lt;br /&gt;            public OnOfflineAnnouncementAsyncResult(AsyncCallback callback, object state)&lt;br /&gt;                : base(callback, state)&lt;br /&gt;            {&lt;br /&gt;                this.Complete(true);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public static void End(IAsyncResult result)&lt;br /&gt;            {&lt;br /&gt;                AsyncResult.End&lt;OnOfflineAnnouncementAsyncResult&gt;(result);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        sealed class OnFindAsyncResult : AsyncResult&lt;br /&gt;        {&lt;br /&gt;            public OnFindAsyncResult(AsyncCallback callback, object state)&lt;br /&gt;                : base(callback, state)&lt;br /&gt;            {&lt;br /&gt;                this.Complete(true);&lt;br /&gt;            }&lt;br /&gt;    &lt;br /&gt;            public static void End(IAsyncResult result)&lt;br /&gt;            {&lt;br /&gt;                AsyncResult.End&lt;OnFindAsyncResult&gt;(result);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    &lt;br /&gt;        sealed class OnResolveAsyncResult : AsyncResult&lt;br /&gt;        {&lt;br /&gt;            EndpointDiscoveryMetadata matchingEndpoint;&lt;br /&gt;    &lt;br /&gt;            public OnResolveAsyncResult(EndpointDiscoveryMetadata matchingEndpoint, AsyncCallback callback, object state)&lt;br /&gt;                : base(callback, state)&lt;br /&gt;            {&lt;br /&gt;                this.matchingEndpoint = matchingEndpoint;&lt;br /&gt;                this.Complete(true);&lt;br /&gt;            }&lt;br /&gt;    &lt;br /&gt;            public static EndpointDiscoveryMetadata End(IAsyncResult result)&lt;br /&gt;            {&lt;br /&gt;                OnResolveAsyncResult thisPtr = AsyncResult.End&lt;OnResolveAsyncResult&gt;(result);&lt;br /&gt;                return thisPtr.matchingEndpoint;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice that I am getting the binding information in the code below:&lt;br /&gt;&lt;code&gt;XElement element = endpointDiscoveryMetadata.Extensions.Elements("BindingData").FirstOrDefault();&lt;br /&gt;string bindingInfo = element.Value;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Now I have the binding information, so when I ask for a specific contract, I can get the binding as well as the address back to the client that is requesting the endpoint information. Now we can discover the full A B C and not just the A and C.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-3777265368189063003?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/3777265368189063003/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=3777265368189063003' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3777265368189063003'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3777265368189063003'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2010/04/wcf-40-service-discovery-adding-binding.html' title='WCF 4.0 Service Discovery - Adding the binding to the discovery'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-4903620784346309630</id><published>2009-09-19T07:25:00.000-07:00</published><updated>2009-09-19T08:10:00.231-07:00</updated><title type='text'>WAS hosting for services with multiple msmq binding endpoints - not ideal!</title><content type='html'>I have been looking into this issue of hosting a service with multiple message queue endpoints with WAS for sometime. One thing that kept bothering me is that the SVC file name of the service needed to match the name of the queue. Furthermore, it was not just the name of the queue, but the name of the virtual folder + the queue name so the activation service will detect messages in my queue and then activate my service.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Once I got all the pieces to work, I renamed my SVC file, checked the permission of my queue to allow the activation service to peek into it, and got the service hosted in WAS, I realized that I can't get another queue on the same service to work. Considering the SVC file needs to match the queue, only one endpoint is satisfied, having another queue endpoint is possible, but the activation service will not look at it. This means that the service will process messages of another queue, but the service will not be activated based on these other queues. So you will need to first activate the service using the SVC named queue, and then the other queues will work.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This means that if you try to host a service with multiple queue endpoints, you must choose which queue will be responsible for the activation of the service. Only one must be chosen (and that queue needs to have the SVC file name renamed after it). Other queues, will not force activation of the service.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I have confirmed this to be true with Micrsofot support. They couldn't even give a good explanation why this was done this way. Why do you need to rename the SVC file? why can't you just use a configuration? or read the metadata of the service... I can think of many other ways to handle activation of queues, without the limitation of one queue per service, and forcing the user to rename his SVC file.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So how do you handle a service with multiple queue endpoints? Well, one simple way is not to use WAS hosting and use Windows Service Hosting, this problem does not exist with non-was hosting, but you loose on the activation model. You can make your own activation model, but that's like re-doing WAS.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Another option if you like using WAS, is to create multiple SVC files, one named after each queue within your service. The SVC files will all point to the same service class / assembly, but it will cause multiple service instances to be created depending on which queue forced the activation. You place all these SVC files within the same virtual folder. This might work only if the service is completely stateless. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Other work-around is to make sure the idle timeout is really large, so your service is only activated once, and then stays alive "forever". But, that just takes the activation out of WAS, which at that point, you may as well host it within a windows service.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Microsoft support also told me, that you can "ping" your service, to make sure it is activated, but that's just crazy... so I will not write more about  that option.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Or... you can simply avoid having multiple queues in the same service (if you are planning to host your service under WAS).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I plan to update this post with an official KB article explaining this issue. Microsoft Support told me they will send it to me once they all agree this is a limitation by design.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Although this is not a popular feature of WAS, I feel there might be others out there trying the very same thing I am trying. I hope this helps them a little bit.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-4903620784346309630?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/4903620784346309630/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=4903620784346309630' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4903620784346309630'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4903620784346309630'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/09/was-hosting-for-services-with-multiple.html' title='WAS hosting for services with multiple msmq binding endpoints - not ideal!'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-5805293888960578509</id><published>2009-08-18T19:11:00.000-07:00</published><updated>2009-08-18T19:15:11.402-07:00</updated><title type='text'>Pub / Sub with WCF and Silverlight 3.0 (using polling duplex)</title><content type='html'>A good exmaple to check out&lt;br /&gt;&lt;a href="http://tomasz.janczuk.org/2009/07/pubsub-sample-using-http-polling-duplex.html"&gt;http://tomasz.janczuk.org/2009/07/pubsub-sample-using-http-polling-duplex.html&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-5805293888960578509?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/5805293888960578509/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=5805293888960578509' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5805293888960578509'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5805293888960578509'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/08/pub-sub-with-wcf-and-silverlight-30.html' title='Pub / Sub with WCF and Silverlight 3.0 (using polling duplex)'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-8492505725772438910</id><published>2009-08-14T11:07:00.000-07:00</published><updated>2009-08-14T11:10:13.041-07:00</updated><title type='text'>GetHashCode using MD5</title><content type='html'>Wanted to have a way to get a hash code for an object, and the code will be different when the data within the object changes. Only supported for objects that support serialization... but it is better then nothing...&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public static class HashCodeGenerator&lt;br /&gt;   {&lt;br /&gt;      public static string GetMD5HashCode(this object obj)&lt;br /&gt;      {&lt;br /&gt;         MemoryStream stream = new MemoryStream();&lt;br /&gt;         BinaryFormatter formatter = new BinaryFormatter();&lt;br /&gt;         formatter.Serialize(stream, obj);&lt;br /&gt;         stream.Flush();&lt;br /&gt;         var data = stream.ToArray();&lt;br /&gt;         StringBuilder sBuilder = new StringBuilder();&lt;br /&gt;&lt;br /&gt;         // get the hash code of the object.&lt;br /&gt;         MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();&lt;br /&gt;         var hashBytesArray =  md5.ComputeHash(data);&lt;br /&gt;&lt;br /&gt;         // Loop through each byte of the hashed data &lt;br /&gt;         // and format each one as a hexadecimal string.&lt;br /&gt;         for (int i = 0; i &lt; hashBytesArray.Length; i++)&lt;br /&gt;         {&lt;br /&gt;            sBuilder.Append(hashBytesArray[i].ToString("x2"));&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         return sBuilder.ToString();&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public static bool CompareMD5HashCode(this object obj, string hashCode)&lt;br /&gt;      {&lt;br /&gt;         string hash = obj.GetMD5HashCode();&lt;br /&gt;         bool isMatch = false;&lt;br /&gt;         if (hash == hashCode)&lt;br /&gt;            isMatch = true;&lt;br /&gt;&lt;br /&gt;         return isMatch;        &lt;br /&gt;      }      &lt;br /&gt;   }&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-8492505725772438910?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/8492505725772438910/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=8492505725772438910' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8492505725772438910'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8492505725772438910'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/08/gethashcode-using-md5.html' title='GetHashCode using MD5'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1951899207060789096</id><published>2009-08-13T17:54:00.000-07:00</published><updated>2009-08-13T17:56:18.343-07:00</updated><title type='text'>Object to XML and XML to Object</title><content type='html'>I always need this code... so now its on my page!&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   internal static class XmlSerializerHelper&lt;br /&gt;   {&lt;br /&gt;      public static object GetObjectFromXml(string xml, Type type)&lt;br /&gt;      {&lt;br /&gt;         XmlSerializer ser = new XmlSerializer(type);&lt;br /&gt;         object value = ser.Deserialize(new StringReader(xml));&lt;br /&gt;         return value;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public static string GetXmlFromObj(object obj, Type type)&lt;br /&gt;      {&lt;br /&gt;         string xml;&lt;br /&gt;         XmlSerializer ser = new XmlSerializer(type);&lt;br /&gt;         using (StringWriter writer = new StringWriter())&lt;br /&gt;         {&lt;br /&gt;            ser.Serialize(writer, obj);&lt;br /&gt;            writer.Flush();&lt;br /&gt;            xml = writer.ToString();&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         return xml;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public static string ToXml(this object obj)&lt;br /&gt;      {&lt;br /&gt;         Type type = obj.GetType();&lt;br /&gt;         string xml = GetXmlFromObj(obj, type);&lt;br /&gt;         return xml;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1951899207060789096?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1951899207060789096/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1951899207060789096' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1951899207060789096'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1951899207060789096'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/08/object-to-xml-and-xml-to-object.html' title='Object to XML and XML to Object'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-8638756148918809558</id><published>2009-08-13T17:12:00.000-07:00</published><updated>2009-08-14T11:07:25.713-07:00</updated><title type='text'>DataForm Control supporting nested classes</title><content type='html'>&lt;p&gt;&lt;br /&gt;One of the cool things in the toolkit is a new DataForm control. You can give it any object and it will produce a form that will allow you to edit / read your object. However, I noticed that the DataForm, out of the box does not support "auto generation" of fields for nested complex types. This is something that sounds simple to support out of the box, becasue a nested class is really another DataForm control nested within its parent DataForm. Still, when tyring to put a complex type, the Dataform control simply puts a textbox and put the ToString() value of your complex type as its value. Not very useful.&lt;br /&gt;&lt;br /&gt;With the help of the UI guy at my work, we found a way to change this limitation and allow for nested UI. I will include the code in this post, but it is mostly testing code and prototype code. You can take it and modify it for your needs.&lt;br /&gt;&lt;br /&gt;To do this we creaed a SuperDataForm control&lt;/p&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Net;&lt;br /&gt;using System.Windows;&lt;br /&gt;using System.Windows.Controls;&lt;br /&gt;using System.Windows.Documents;&lt;br /&gt;using System.Windows.Ink;&lt;br /&gt;using System.Windows.Input;&lt;br /&gt;using System.Windows.Media;&lt;br /&gt;using System.Windows.Media.Animation;&lt;br /&gt;using System.Windows.Shapes;&lt;br /&gt;using System.Windows.Data;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;&lt;br /&gt;namespace ParameterManagement&lt;br /&gt;{&lt;br /&gt;   public class SuperDataForm : DataForm&lt;br /&gt;   {&lt;br /&gt;      List&lt;superdataform&gt; Controls = new List&lt;superdataform&gt;();&lt;br /&gt;&lt;br /&gt;      public bool CompositeItemIsValid;&lt;br /&gt;      public SuperDataForm()&lt;br /&gt;      {     &lt;br /&gt;         this.Loaded += new RoutedEventHandler(SuperDataForm_Loaded);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      void SuperDataForm_Loaded(object sender, RoutedEventArgs e)&lt;br /&gt;      {&lt;br /&gt;         if (this.CurrentItem == null)&lt;br /&gt;         {&lt;br /&gt;            this.CurrentItem = this.DataContext;&lt;br /&gt;         }     &lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      protected override void OnAutoGeneratingField(DataFormAutoGeneratingFieldEventArgs e)&lt;br /&gt;      {&lt;br /&gt;         // normally change this condition to check it is one of your complex types&lt;br /&gt;         // or that it is not a basic type.&lt;br /&gt;         if (e.PropertyType == typeof(NestedComplexType))&lt;br /&gt;         {&lt;br /&gt;            var control = new SuperDataForm();&lt;br /&gt;&lt;br /&gt;            control.CommandButtonsVisibility = DataFormCommandButtonsVisibility.All;&lt;br /&gt;            control.IsReadOnly = false;&lt;br /&gt;            Controls.Add(control);&lt;br /&gt;            Binding binding = new Binding(e.PropertyName);&lt;br /&gt;            binding.Mode = BindingMode.TwoWay;&lt;br /&gt;            binding.ValidatesOnExceptions = true;&lt;br /&gt;            binding.NotifyOnValidationError = true;&lt;br /&gt;            control.SetBinding(DataForm.CurrentItemProperty, binding);&lt;br /&gt;            e.Field.IsReadOnly = false;&lt;br /&gt;            e.Field.Content = control;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      protected override void OnValidatingItem(System.ComponentModel.CancelEventArgs e)&lt;br /&gt;      {&lt;br /&gt;         // this is needed to have validation on the children controls&lt;br /&gt;         foreach (var control in Controls)&lt;br /&gt;         {&lt;br /&gt;            if (!control.ValidateItem())&lt;br /&gt;            {&lt;br /&gt;               CompositeItemIsValid = false;&lt;br /&gt;               break;&lt;br /&gt;            }         &lt;br /&gt;         }                &lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      protected override void OnCurrentItemChanged(EventArgs e)&lt;br /&gt;      {&lt;br /&gt;     &lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://mike.peretz.googlepages.com/ParameterManagement.zip"&gt;Download Code Here&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-8638756148918809558?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/8638756148918809558/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=8638756148918809558' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8638756148918809558'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8638756148918809558'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/08/dataform-control.html' title='DataForm Control supporting nested classes'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1025427405964581276</id><published>2009-05-15T20:43:00.000-07:00</published><updated>2009-05-15T20:51:47.519-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Bug'/><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='IE6'/><title type='text'>Silverlight 2.0 + IE6 + Compression - BUG!</title><content type='html'>I have been running into a problem with Silverlight 2.0 when dynamic compression was set on IIS7. I found out that the issue was only with IE6 and not with IE7. After googling for some time I found this article… &lt;a href="http://otoole.wordpress.com/2009/03/10/18/"&gt;http://otoole.wordpress.com/2009/03/10/18/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;After trying a few things in the article like setting caching off, I decided to call Microsoft and hear what they have to say about all this.&lt;br /&gt;&lt;br /&gt;Microsoft replied, and said this is a bug with IE6. What makes things worst is that the bug has no work-around or solution. The only solution will be in Silverlight 3.0, and even that is considered a work-around to the real bug which is in IE6.&lt;br /&gt;&lt;br /&gt;At the end, the only way to get our Silverlight app to work with IE6 was to turn compression off, which caused some performance issues…&lt;br /&gt;&lt;br /&gt;The issue with Microsoft is still open; I have asked them to validate IE8 and the use of SSL, which has been causing problems too…&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1025427405964581276?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1025427405964581276/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1025427405964581276' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1025427405964581276'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1025427405964581276'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/05/silverlight-20-ie6-compression-bug.html' title='Silverlight 2.0 + IE6 + Compression - BUG!'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-9063045477623006452</id><published>2009-04-19T10:28:00.000-07:00</published><updated>2009-04-19T10:31:57.949-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Template'/><category scheme='http://www.blogger.com/atom/ns#' term='Singleton'/><title type='text'>Generic Singleton method</title><content type='html'>This is a general purpose method to create a singleton. It uses generics and takes two arguments, one is the type of the singleton and the other is the type of the interface you wish to return (this is optional). Notice that the method is thread safe, there is a double check to verify that another thread did not create instance after the first if statement. The idea is to have the lock done only once if possible.&lt;br /&gt;&lt;br /&gt;Code looks like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;      private static TInterface GetSingleton&lt;tinterface,&gt;(ref TInterface instance)&lt;br /&gt;         where TComponent : class, TInterface, new()&lt;br /&gt;      {&lt;br /&gt;         try&lt;br /&gt;         {&lt;br /&gt;            if (instance == null)&lt;br /&gt;            {&lt;br /&gt;               lock (mLockObject)&lt;br /&gt;               {&lt;br /&gt;                  if (instance == null)&lt;br /&gt;                  {&lt;br /&gt;                     instance = new TComponent();&lt;br /&gt;                  }&lt;br /&gt;               }&lt;br /&gt;            }&lt;br /&gt;            return instance;&lt;br /&gt;         }&lt;br /&gt;         catch (Exception ex)&lt;br /&gt;         {&lt;br /&gt;            LogException(ex);&lt;br /&gt;            throw ex;&lt;br /&gt;         }&lt;br /&gt;      }&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-9063045477623006452?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/9063045477623006452/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=9063045477623006452' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/9063045477623006452'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/9063045477623006452'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/04/generic-singleton-method.html' title='Generic Singleton method'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-8484060401128810233</id><published>2009-03-15T11:17:00.001-07:00</published><updated>2009-04-19T10:20:38.413-07:00</updated><title type='text'>Jitting at runtime (Jit methods on the fly)</title><content type='html'>&lt;h2&gt;What is Jit&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Jit stands for Just in time complication. You can read more about JIT &lt;a href=http://en.wikipedia.org/wiki/Just-in-time_compilation&gt;here&lt;/a&gt;. However, the idea is that the&lt;br /&gt;code is not fully complied, it is pre-complied. The first time your method is executed, the .NET runtime checks if the method has been complied for the target machine, if it did not then it compiles it on the fly. This is called JIT. This behaviour also causes a delay when executing methods for the first time. The bigger the method, the bigger the delay. I have noticed this delay the most when doing UI applications, the generated code would take a long time to JIT. You can also add performance counters to see how much time your application is jitting. In fact most classes that use generated code, can be good candidate for jitting (typed dataset, UI screens, EDMX...)&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;NGen&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;NGen is the alternative solution to runtime Jitting. Everything is complied by the NGen tool and a compiled image is placed within the GAC. At runtime when loading the assembly, the runtime will check for a compiled image based on the assembly name and version, if it finds one it will load it without Jitting. Still, NGen needs to run on the target machine before running the application. NGen is also not as efficient as Jit, that's because Jit executes at runtime and has much more information about the method and how to optimize it. You can read more about NGen &lt;a href=http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Is it possible to control the Jitting&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;I always wanted to have something to control the jitting at runtime. Similar to the GC class, I can control at runtime when the GC is executed, there is not built in class called Jit that will allow me to Jit certain methods. However, it is possible. The method that allows for this type of functionality is &lt;code&gt;RuntimeHelpers.PrepareMethod Method (RuntimeMethodHandle)&lt;/code&gt;. However, here is a little warning for you all, in the MSDN article it indicates: &lt;I&gt;The classes in System.Runtime.CompilerServices are for compiler writers' use only.&lt;/I&gt;. Still, I decided to use it, there are times that I would like to control when Jitting happens.&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;JitHelper and the PreJit attribute&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;The idea is very simple. I want to have a helper class that will jit any method that is marked with an attribute of PreJit. Normally the coder knows which are the heavy methods, this way the coder has the control of marking methods that can take long to jit. For example:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;        [PreJit]&lt;br /&gt;        private void InitializeComponent()&lt;br /&gt;        {&lt;br /&gt;            this.components = new System.ComponentModel.Container();&lt;br /&gt;            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;&lt;br /&gt;            this.Text = "Form1";&lt;br /&gt;        }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice the PreJit attribute on the method.&lt;br /&gt;&lt;br /&gt;PreJit is just a marker attribute. Here is the code for it.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    [AttributeUsage(AttributeTargets.Method)]&lt;br /&gt;    public class PreJitAttribute : Attribute&lt;br /&gt;    {&lt;br /&gt;        public PreJitAttribute()&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Now, all that is left to do is Jit the methods that are marked with the &lt;code&gt;[PreJit]&lt;/code&gt; attribute. Lets take a look at one method that handle jitting based on the type of a CLR class.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;        private static void PreJitMarkedMethods(Type type)&lt;br /&gt;        {&lt;br /&gt;            // get the type of all the methods within this instance&lt;br /&gt;            var methods = type.GetMethods(BindingFlags.DeclaredOnly |&lt;br /&gt;                                        BindingFlags.NonPublic |&lt;br /&gt;                                        BindingFlags.Public |&lt;br /&gt;                                        BindingFlags.Instance |&lt;br /&gt;                                        BindingFlags.Static);&lt;br /&gt;&lt;br /&gt;            // for each time, jit methods marked with prejit attribute&lt;br /&gt;            foreach (var method in methods)&lt;br /&gt;            {&lt;br /&gt;                // checks if the [PreJit] Attribute is present&lt;br /&gt;                if (ContainsPreJitAttribute(method))&lt;br /&gt;                {&lt;br /&gt;                    // jitting of the method happends here.&lt;br /&gt;                    RuntimeHelpers.PrepareMethod(method.MethodHandle);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // (helper method) checks if the [PreJit] attribute is present on a method&lt;br /&gt;        private static bool ContainsPreJitAttribute(MethodInfo methodInfo)&lt;br /&gt;        {&lt;br /&gt;            var attributes = methodInfo.GetCustomAttributes(typeof(PreJitAttribute), false);&lt;br /&gt;            if (attributes != null)&lt;br /&gt;                if (attributes.Length &gt; 0)&lt;br /&gt;                {&lt;br /&gt;                    // attribute found return true&lt;br /&gt;                    return true;&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Lets note the important stuff. This method is able to jit all marked methods with the PreJit attribute based on a CLR type&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;Getting all methods, private, public and even static&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Only Jit methods that have an attribute of &lt;code&gt;[PreJit]&lt;/code&gt;&lt;br /&gt;   &lt;li&gt;On each method we get the MethodInfo object&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Passing MethodInfo.MethodHandle to PrepareMethod allows us to jit a method&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;The Jitter&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now that it is possible for me to jit every method within a type, all I have to do is create high level&lt;br /&gt;methods that will allow me to do the following:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;Jit only methods that are marked with PreJit attribute&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Jit on a different thread&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Jit based on an instance (Jit methods within the instance)&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Jit based on a Type (Jit methods for a given class type)&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Jit based on an assembly (Jit methods within all the classes in an assembly&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Lets see the full class code for the Jitter&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using System.Reflection;&lt;br /&gt;using System.Threading;&lt;br /&gt;using System.Runtime.CompilerServices;&lt;br /&gt;&lt;br /&gt;namespace JitHelper&lt;br /&gt;{&lt;br /&gt;    public class Jitter&lt;br /&gt;    {&lt;br /&gt;        public static void PreJit(object instance)&lt;br /&gt;        {&lt;br /&gt;            PreJitMarkedMethods(instance.GetType());&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public static void PreJitAll(object instance)&lt;br /&gt;        {&lt;br /&gt;            PreJitAllMethods(instance.GetType());&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void BeginPreJitAll(object instance)&lt;br /&gt;        {&lt;br /&gt;            Thread preJitThread = new Thread(() =&gt;&lt;br /&gt;            {&lt;br /&gt;                PreJitAllMethods(instance.GetType());&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;            preJitThread.Name = "PreJittingThread";&lt;br /&gt;            preJitThread.Priority = ThreadPriority.Lowest;&lt;br /&gt;            preJitThread.Start();&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void PreJit&lt;T&gt;() where T : class&lt;br /&gt;        {&lt;br /&gt;            PreJitMarkedMethods(typeof(T));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public static void PreJitAll&lt;T&gt;() where T : class&lt;br /&gt;        {&lt;br /&gt;            PreJitAllMethods(typeof(T));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void BeginPreJitAll&lt;T&gt;() where T : class&lt;br /&gt;        {&lt;br /&gt;            Thread preJitThread = new Thread(() =&gt;&lt;br /&gt;            {&lt;br /&gt;                PreJitAllMethods(typeof(T));&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;            preJitThread.Name = "PreJittingThread";&lt;br /&gt;            preJitThread.Priority = ThreadPriority.Lowest;&lt;br /&gt;            preJitThread.Start();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void PreJitAll(Assembly assembly)&lt;br /&gt;        {&lt;br /&gt;            var classes = assembly.GetTypes();&lt;br /&gt;            foreach (var classType in classes)&lt;br /&gt;            {&lt;br /&gt;                PreJitAllMethods(classType);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void BeginPreJitAll(Assembly assembly)&lt;br /&gt;        {&lt;br /&gt;            Thread preJitThread = new Thread(() =&gt;&lt;br /&gt;            {&lt;br /&gt;                PreJitAll(assembly);&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;            preJitThread.Name = "PreJittingThread";&lt;br /&gt;            preJitThread.Priority = ThreadPriority.Lowest;&lt;br /&gt;            preJitThread.Start();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public static void PreJit(Assembly assembly)&lt;br /&gt;        {&lt;br /&gt;            var classes = assembly.GetTypes();&lt;br /&gt;            foreach (var classType in classes)&lt;br /&gt;            {&lt;br /&gt;                PreJitMarkedMethods(classType);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public static void BeginPreJit(Assembly assembly)&lt;br /&gt;        {&lt;br /&gt;            Thread preJitThread = new Thread(() =&gt;&lt;br /&gt;            {&lt;br /&gt;                PreJit(assembly);&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;            preJitThread.Name = "PreJittingThread";&lt;br /&gt;            preJitThread.Priority = ThreadPriority.Lowest;&lt;br /&gt;            preJitThread.Start();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static void BeginPreJit(object instance)&lt;br /&gt;        {&lt;br /&gt;            Thread preJitThread = new Thread(() =&gt;&lt;br /&gt;            {&lt;br /&gt;                PreJit(instance);&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;            preJitThread.Name = "PreJittingThread";&lt;br /&gt;            preJitThread.Priority = ThreadPriority.Lowest;&lt;br /&gt;            preJitThread.Start();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private static void PreJitMarkedMethods(Type type)&lt;br /&gt;        {&lt;br /&gt;            // get the type of all the methods within this instance&lt;br /&gt;            var methods = type.GetMethods(BindingFlags.DeclaredOnly |&lt;br /&gt;                                        BindingFlags.NonPublic |&lt;br /&gt;                                        BindingFlags.Public |&lt;br /&gt;                                        BindingFlags.Instance |&lt;br /&gt;                                        BindingFlags.Static);&lt;br /&gt;&lt;br /&gt;            // for each time, jit methods marked with prejit attribute&lt;br /&gt;            foreach (var method in methods)&lt;br /&gt;            {&lt;br /&gt;                if (ContainsPreJitAttribute(method))&lt;br /&gt;                {&lt;br /&gt;                    // jitting of the method happends here.&lt;br /&gt;                    RuntimeHelpers.PrepareMethod(method.MethodHandle);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private static void PreJitAllMethods(Type type)&lt;br /&gt;        {&lt;br /&gt;            // get the type of all the methods within this instance&lt;br /&gt;            var methods = type.GetMethods(BindingFlags.DeclaredOnly |&lt;br /&gt;                                        BindingFlags.NonPublic |&lt;br /&gt;                                        BindingFlags.Public |&lt;br /&gt;                                        BindingFlags.Instance |&lt;br /&gt;                                        BindingFlags.Static);&lt;br /&gt;&lt;br /&gt;            // Jit all methods&lt;br /&gt;            foreach (var method in methods)&lt;br /&gt;            {&lt;br /&gt;                // jitting of the method happends here.&lt;br /&gt;                RuntimeHelpers.PrepareMethod(method.MethodHandle);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private static bool ContainsPreJitAttribute(MethodInfo methodInfo)&lt;br /&gt;        {&lt;br /&gt;            var attributes = methodInfo.GetCustomAttributes(typeof(PreJitAttribute), false);&lt;br /&gt;            if (attributes != null)&lt;br /&gt;                if (attributes.Length &gt; 0)&lt;br /&gt;                {&lt;br /&gt;                    return true;&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;A few notes about the code:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;Methods beginning with "Begin" are executed on a low priority thread. This allows for background jitting. I have not done a callback feature to know when jitting ends, I don't think it is required, but you are free to modify the class and add it.&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Method ending with "All", will Jit all methods and not just the one marked as PreJit attribute&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Not all methods can be PreJit, for example methods marked as &lt;code&gt;DllExport&lt;/code&gt; are not .NET methods, so be careful with the All feature. For performance reasons I have not checked for DllExport attribute, but you can add it if needed.&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Notice that one method uses generics, this is simply so the caller can pass the type via generic without doing typeof operator.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Using the Jitter&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;I will simply show you an exmaple, the following example everything within &lt;code&gt;Form1&lt;/code&gt; is pre-Jitted.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;        [STAThread]&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            // Jitting all the methods within Form1 class.&lt;br /&gt;            Jitter.PreJitAll&lt;Form1&gt;();&lt;br /&gt;            Application.EnableVisualStyles();&lt;br /&gt;            Application.SetCompatibleTextRenderingDefault(false);&lt;br /&gt;            Application.Run(new Form1());&lt;br /&gt;        }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;if you want to pre-jit within a thread, then simply use:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;        [STAThread]&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            Jitter.BeginPreJitAll&lt;Form1&gt;();&lt;br /&gt;            Application.EnableVisualStyles();&lt;br /&gt;            Application.SetCompatibleTextRenderingDefault(false);&lt;br /&gt;            Application.Run(new Form1());&lt;br /&gt;        }&lt;/pre&gt;&lt;br /&gt;        &lt;br /&gt;&lt;h2&gt;Benchmarking&lt;/h2&gt;&lt;br /&gt;It is not that simple to benchmark this type of code because it really depends how your application works. However, the Jit operation happends the first time a method is executed. So the first time of any method will cause a delay. I have created a windows form full of text boxes controls, and I used the Jitter to Jit everything within the form class. On the form show event I display the time it took to show the form:&lt;br /&gt;&lt;br /&gt;Without using the jitter:  ~0.12 milliseconds&lt;br /&gt;With the Jitter:           ~0.12 milliseconds&lt;br /&gt;Timing after Jitting:      ~0.09 milliseconds&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;With the Jitter or without it, it took about the same amount of time to show the form. &lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Without timing the Jitter, just the load operation after the Jit, it took 0.09 miliseconds to show&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Overall it means that the Jitter class can have a significate performance improvment at runtime, if a class is jitted before it is being used.&lt;br /&gt;&lt;/ul&gt;   &lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Let me first say that I coded this class mostly because I wanted to have the control over Jitting. But overall .NET runtime does a very good job Jitting when needed. The same way we should not call &lt;code&gt;GC.Collect()&lt;/code&gt; we should not call Jitting functions. Having said that, there are times it would be nice to control Jitting and have an alternative to NGen. Use this tool only if you have a performance issue, or a startup timing issue. If you do not have a performance issue - do not use this. This class also uses reflection to find out the methods to Jit. Reflection is slow, which is another reason to avoid using this class unless required. You should consider trying pre-jitting your classes when you are using generated code classes, such as typed dataset, LINQ to entities, or winform UI classes.&lt;br /&gt;&lt;br /&gt;Even if you are not planning to use the Jitter class, it is better to have the Jitter class and not need it, then need it and not have it.&lt;br /&gt;&lt;br /&gt;Thank you for reading. Have a nice day, and happy .Netting.&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul class="Download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="Jitting/JitHelper.zip"&gt;Download JitHelper - 91.23 KB&lt;/a&gt; &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-8484060401128810233?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/8484060401128810233/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=8484060401128810233' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8484060401128810233'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8484060401128810233'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/03/jitting-at-runtime.html' title='Jitting at runtime (Jit methods on the fly)'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-6095584025505086272</id><published>2009-01-28T14:42:00.001-08:00</published><updated>2009-01-28T14:45:42.694-08:00</updated><title type='text'>SDF (Compact sql database) with .NET 3.5SP1 Buggy with Entity Framework</title><content type='html'>I just can't believe Microsoft will ship this &lt;span class="blsp-spelling-corrected" id="SPELLING_ERROR_0"&gt;technology&lt;/span&gt; with such major bugs within it. If you are looking into &lt;span class="blsp-spelling-error" id="SPELLING_ERROR_1"&gt;SDF &lt;/span&gt;files with support of entity framework, you might want to look into the major bugs they are having. For &lt;span class="blsp-spelling-corrected" id="SPELLING_ERROR_2"&gt;example&lt;/span&gt;, you will not be able to use a string variable in a compare operation with a &lt;span class="blsp-spelling-error" id="SPELLING_ERROR_3"&gt;LINQ&lt;/span&gt; &lt;span class="blsp-spelling-corrected" id="SPELLING_ERROR_4"&gt;statement&lt;/span&gt;. Sounds basic, but still it does not work. Look at the blob on this bug&lt;br /&gt;&lt;br /&gt;&lt;a href="http://social.msdn.microsoft.com/forums/en-US/sqlce/thread/b6bac277-cf66-4c74-a0b3-e48abedbd161/"&gt;http://social.msdn.microsoft.com/forums/en-US/sqlce/thread/b6bac277-cf66-4c74-a0b3-e48abedbd161/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I wonder if Microsoft forgot to unit-test this stuff before shipping.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-6095584025505086272?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/6095584025505086272/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=6095584025505086272' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/6095584025505086272'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/6095584025505086272'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/01/sdf-compact-sql-database-with-net-35sp1.html' title='SDF (Compact sql database) with .NET 3.5SP1 Buggy with Entity Framework'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-7492088721661370722</id><published>2009-01-08T05:15:00.000-08:00</published><updated>2009-01-08T05:16:48.965-08:00</updated><title type='text'>How to find an avaiable TCP port</title><content type='html'>&lt;p&gt;This simple method will return the next avaiable TCP port&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;      private static int GetAvaiablePort()&lt;br /&gt;      {&lt;br /&gt;         IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);&lt;br /&gt;         using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))&lt;br /&gt;         {&lt;br /&gt;            socket.Bind(endPoint);&lt;br /&gt;            IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;&lt;br /&gt;            return local.Port;&lt;br /&gt;         }&lt;br /&gt;      }&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-7492088721661370722?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/7492088721661370722/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=7492088721661370722' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/7492088721661370722'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/7492088721661370722'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2009/01/how-to-find-avaiable-tcp-port.html' title='How to find an avaiable TCP port'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1664532776608238284</id><published>2008-12-30T11:03:00.000-08:00</published><updated>2008-12-31T11:09:29.295-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight dmvm dm-v-vm'/><title type='text'>DM-V-VM</title><content type='html'>&lt;h2&gt;Links for DataModel View ViewModel Pattern&lt;/h2&gt;&lt;br /&gt;&lt;a href="https://blogs.msdn.com/dancre/archive/tags/DM-V-VM/default.aspx"&gt;https://blogs.msdn.com/dancre/archive/tags/DM-V-VM/default.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.nikhilk.net/Entry.aspx?id=198"&gt;http://www.nikhilk.net/Entry.aspx?id=198&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx"&gt;http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/"&gt;ICommand for Silverlight with Attached Behaviors&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx"&gt;http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1664532776608238284?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1664532776608238284/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1664532776608238284' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1664532776608238284'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1664532776608238284'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/12/dm-v-vm.html' title='DM-V-VM'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-3162714721530464343</id><published>2008-12-29T14:19:00.000-08:00</published><updated>2008-12-30T11:49:04.993-08:00</updated><title type='text'>Understanding SynchronizationContext Part III</title><content type='html'>&lt;ul class="download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://mike.peretz.googlepages.com/STASyncSolution.zip"&gt;Download STASyncSolution.zip - 55.28 KB &lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;This article is the last part of the 3 part series on SynchronizationContext, SynchronizationContext is a class introduced by .NET 2.0 with little documentation or explanation of how to use it. I have tried to explain in part one how to use this class, and in part two how to create your own SynchronizationContext. In part two, I have showed how to build a SynchronizationContext that will marshal code from any .NET thread into a STA thread. I have done this so I can execute COM code that needs to run on the STA thread. The next step is to&amp;nbsp;create a WCF service that will execute all its service operations on the STA thread (using the SynchronizationContext I provided in part II). In this article, I will show you how to configure WCF to provide a custom&amp;nbsp;STA SynchronizationContext so each method on a WCF service will execute on the same STA thread. This will allow me to provide a simple programming model, that will be fully compatible with COM and I will not need to worry about thread safety because all my code will run within the same thread. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;WCF - The Power&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I will not even try to give a full explanation of WCF here, WCF is vast in functionality and does much more then just &amp;quot;remoting&amp;quot; or web services. I am starting to believe that WCF should be treated as a runtime rather then a communication framework. WCF provides us &amp;quot;out of the box&amp;quot; the following programming models: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;built-in support for error handling &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for concurrency &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for security &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for transaction &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for data encryption &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for durable services &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for method interception and inspection (AOP) &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;built-in support for one way communication, and callbacks &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;and much more... &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Just listen to this arcast, where Juval Lowy believes every class should be a WCF class. &lt;a href="http://channel9.msdn.com/shows/ARCast+with+Ron+Jacobs/ARCastTV-Every-Class-a-WCF-Service-with-Juval-Lowy/" target="_blank"&gt;http://channel9.msdn.com/shows/ARCast+with+Ron+Jacobs/ARCastTV-Every-Class-a-WCF-Service-with-Juval-Lowy/&lt;/a&gt; At first, I said to myself, this is too much, every class to be a WCF class is just insane. But the more I looked at WCF and what it had to offer, the more it made sense to me. WCF is a very extensible framework, allowing the developer to do a lot of custom configuration. For example providing a SynchronizationContext for your service is something you will not be able to do within native .NET classes, but only in WCF (and that's just one feature among many). Although I must say I did not go as far as making each class a WCF class, I have decided to make each component a WCF service, even if I don't plan to run my component remotly, I still believe the benefits of the WCF runtime are worth coding my components as WCF services. Bottom line, WCF is more then web services or remoting services, it provides a solid programming model that apply in every type of development. If you don't know WCF, I strongly recommend you learn it, it is by far one of the better frameworks Micrsooft have released. For this article, I assume you have basic knowledge of WCF services.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;A simple WCF Service&lt;/h2&gt;&lt;br /&gt;Let me just say this right away, I have coded a WCF service for this article just for testing. I do not recommend you code services the way that I have. To be more specific, in my code the service implementation and the service contact are within the same assembly - this is not recommended. However, because I am dealing with testing my SynchronizationContext within a prototype/testing project, I wanted to keep the number of assemblies and code to a minimum. Normally, when I code a WCF service I have 3 projects. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Project containing the service contact (interface) and possibly any data contacts (DTOs) &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Project containing the service implementation &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Project hosting the service (optional) &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;So please no bashing, I am stating it here that the code is just for testing and not for production, now that we got it out of the way, let me show the service contact and implementation &lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;[ServiceContract]&lt;br /&gt;public interface IStaService&lt;br /&gt;{&lt;br /&gt;  [OperationContract]&lt;br /&gt;  string DoWorkOnSTAThread(string state);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;There is really not much to say about this service, it is very simple. Let me show you the implementation of this service&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public class StaService : IStaService&lt;br /&gt;{&lt;br /&gt;  public string DoWorkOnSTAThread(string state)&lt;br /&gt;  {&lt;br /&gt;     ApartmentState aptState = Thread.CurrentThread.GetApartmentState();&lt;br /&gt;     if (aptState == ApartmentState.STA)&lt;br /&gt;        Trace.WriteLine(&amp;quot;Using STA thread&amp;quot;);&lt;br /&gt;&lt;br /&gt;     int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;     Trace.WriteLine(&amp;quot;WCF current thread: &amp;quot; + id);&lt;br /&gt;     return &amp;quot;processed by &amp;quot; + aptState.ToString() + &amp;quot; Thread id: &amp;quot; + id.ToString();&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notes:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;code&gt;DoWorkOnSTAThread&lt;/code&gt; will be the method I plan to execute on the STA thread, so I coded some tracking code to make sure I am running this method on the STA thread. I check the ApartmentState and make sure it is an &lt;code&gt;ApartmentState.STA&lt;/code&gt; &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;I also log the thread ID, considering I want all my code to run on the same STA thread, the ID should always be the same &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;However I did not write any code to indicate using the STA Sync Context, so for now, STA thread marshaling is not used &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Testing our service&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;We will be running our service a few times, so lets learn how to test it. My service is hosted using webdev, and it is running as a web service. To test it, I have used the WCF test client applicaiton.It can normally be found at &lt;strong&gt;&amp;quot;C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\WcfTestClient.exe&amp;quot;&lt;/strong&gt; by calling DoWorkOnSTAThread multiple times, I get the following output&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_cyvneGa_yo8/SVp6QHykpYI/AAAAAAAAFmQ/bWMCB506BOY/s1600-h/WCFClient.jpg"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 200px; height: 127px;" src="http://1.bp.blogspot.com/_cyvneGa_yo8/SVp6QHykpYI/AAAAAAAAFmQ/bWMCB506BOY/s200/WCFClient.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5285671530060359042" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;p&gt;Output window:&lt;/p&gt;&lt;br /&gt;&lt;pre lang="text"&gt;WCF current thread: 12&lt;br /&gt;WCF current thread: 12&lt;br /&gt;WCF current thread: 11&lt;br /&gt;WCF current thread: 11&lt;br /&gt;WCF current thread: 11&lt;br /&gt;WCF current thread: 13&lt;br /&gt;WCF current thread: 10&lt;br /&gt;WCF current thread: 11&lt;br /&gt;WCF current thread: 10&lt;br /&gt;WCF current thread: 10&lt;br /&gt;WCF current thread: 13&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To find out the service behavior, you can view the ServiceDescription within a custom ServiceHost (I will show the custom service host code later in the article)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_cyvneGa_yo8/SVp61NASTQI/AAAAAAAAFmY/l98j7E8pl0w/s1600-h/WCFServiceDescription.jpg"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 200px; height: 100px;" src="http://3.bp.blogspot.com/_cyvneGa_yo8/SVp61NASTQI/AAAAAAAAFmY/l98j7E8pl0w/s200/WCFServiceDescription.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5285672167115214082" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that I am running the same method on multiple threads. This is because by default WCF created my service using PerSession InstanceContextMode and ConcurrencyMode of Single (see image above). This means that the method will be executed one at the time, but each time it is executed by a thread assigned by the thread pool. First, you should avoid using PerSession for your services, PerSession simply does not scale, I consider it evil for coding scalable services, so, I am going to change the service behavior&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;[ServiceBehavior(UseSynchronizationContext=true, ConcurrencyMode=ConcurrencyMode.Multiple,&lt;br /&gt;  InstanceContextMode=InstanceContextMode.PerCall)]&lt;br /&gt;public class StaService : IStaService&lt;br /&gt;{&lt;br /&gt;  public string DoWorkOnSTAThread(string state)&lt;br /&gt;  {&lt;br /&gt;     ApartmentState aptState = Thread.CurrentThread.GetApartmentState();&lt;br /&gt;     if (aptState == ApartmentState.STA)&lt;br /&gt;        Trace.WriteLine(&amp;quot;Using STA thread&amp;quot;);&lt;br /&gt;&lt;br /&gt;     int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;     Trace.WriteLine(&amp;quot;WCF current thread: &amp;quot; + id);&lt;br /&gt;     //throw new Exception(&amp;quot;boom&amp;quot;);&lt;br /&gt;     return &amp;quot;processed by &amp;quot; + aptState.ToString() + &amp;quot; Thread id: &amp;quot; + id.ToString();&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Using the WCF service behavior attribute &lt;code&gt;[ServiceBehavior(UseSynchronizationContext=true, ConcurrencyMode=ConcurrencyMode.Multiple, InstanceContextMode=InstanceContextMode.PerCall)]&lt;/code&gt; I ask WCF to create this service using InstanceContextMode.PerCall, this means every method call will create an instance of the service, and as soon as the method completes the instance is destroyed. Using &lt;code&gt;ConcurrencyMode.Multiple&lt;/code&gt; allows for clients to execute methods within this service concurrently, allowing multiple threads to execute the same method at the same time. &lt;code&gt;UseSynchronizationContext=true&lt;/code&gt; means that I ask the service to use the SynchronizationContext attached to the host's thread. Using this new service behavior, lets see our output by executing the method&amp;nbsp;3 times:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="text"&gt;WCF current thread: 12&lt;br /&gt;WCF current thread: 9&lt;br /&gt;WCF current thread: 6&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Same results more or less... Our service can scale better, but still have no control on which thread the code is executed on. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Providing your service a SynchronizationContext&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;You noticed that no matter if the service is using single or multiple concurrency mode, in both the invocation is controlled by WCF using different threads from the thread pool. In order to provide your own SynchronizationContext you have two choices: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Set the SynchronizationContext on the hosting thread before opening the host &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Create your own ServiceBehavior and override the SynchronizationContext on the service endpoint &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I will explore the second option simply because we don't always create our own hosting program and in many cases the hosting is done in WAS or IIS. Let me show you the ServiceBehvior attribute I created to use STA thread synchronization. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public class StaServiceBehaviorAttribute : Attribute, IContractBehavior, IServiceBehavior&lt;br /&gt;{&lt;br /&gt;  StaSynchronizationContext mStaContext;&lt;br /&gt;  public StaServiceBehaviorAttribute()&lt;br /&gt;  {&lt;br /&gt;     mStaContext = new StaSynchronizationContext();&lt;br /&gt;  }&lt;br /&gt;  #region IContractBehavior Members&lt;br /&gt;&lt;br /&gt;  void IContractBehavior.AddBindingParameters(ContractDescription contractDescription, &lt;br /&gt;    ServiceEndpoint endpoint, &lt;br /&gt;    System.ServiceModel.Channels.BindingParameterCollection bindingParameters)&lt;br /&gt;  {&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void IContractBehavior.ApplyClientBehavior(ContractDescription contractDescription,&lt;br /&gt;    ServiceEndpoint endpoint, &lt;br /&gt;    System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)&lt;br /&gt;  {&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void IContractBehavior.ApplyDispatchBehavior(ContractDescription contractDescription,&lt;br /&gt;    ServiceEndpoint endpoint,&lt;br /&gt;    System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)&lt;br /&gt;  {&lt;br /&gt;     dispatchRuntime.SynchronizationContext = mStaContext;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void IContractBehavior.Validate(ContractDescription contractDescription, &lt;br /&gt;    ServiceEndpoint endpoint)&lt;br /&gt;  {&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  #endregion&lt;br /&gt;&lt;br /&gt;  #region IServiceBehavior Members&lt;br /&gt;&lt;br /&gt;  void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription,&lt;br /&gt;    System.ServiceModel.ServiceHostBase serviceHostBase,&lt;br /&gt;    System.Collections.ObjectModel.Collection&lt;serviceendpoint /&gt; endpoints,&lt;br /&gt;    System.ServiceModel.Channels.BindingParameterCollection bindingParameters)&lt;br /&gt;  {&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, &lt;br /&gt;    System.ServiceModel.&lt;br /&gt;    ServiceHostBase serviceHostBase)&lt;br /&gt;  {&lt;br /&gt;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void IServiceBehavior.Validate(ServiceDescription serviceDescription, &lt;br /&gt;    System.ServiceModel.ServiceHostBase serviceHostBase)&lt;br /&gt;  {&lt;br /&gt;     serviceHostBase.Closed += delegate&lt;br /&gt;     {&lt;br /&gt;        mStaContext.Dispose();&lt;br /&gt;     };&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  #endregion&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;By creating my own custom ServiceBehvior attribute I can set certain settings that are otherwise not available to me. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that I am creating the &lt;code&gt;StaSynchronizationContext&lt;/code&gt; at the constructor&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public StaServiceBehaviorAttribute()&lt;br /&gt;{&lt;br /&gt;    mStaContext = new StaSynchronizationContext();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The other most important part is implementing the &lt;code&gt;ApplydispatchBehvior&lt;/code&gt; method. This method will be executed once on each endpoint within your service. It allows me to override the default SynchronizationContext with my own custom one. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;void IContractBehavior.ApplyDispatchBehavior(ContractDescription contractDescription,&lt;br /&gt;    ServiceEndpoint endpoint,&lt;br /&gt;    System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)&lt;br /&gt;{&lt;br /&gt;    dispatchRuntime.SynchronizationContext = mStaContext;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To make sure my STA thread ends correctly, I have also modified the IServiceBehavior.Validate and provided an event handler for closing the host&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;void IServiceBehavior.Validate(ServiceDescription serviceDescription,&lt;br /&gt;     System.ServiceModel.ServiceHostBase serviceHostBase)&lt;br /&gt;{&lt;br /&gt; serviceHostBase.Closed += delegate&lt;br /&gt; {&lt;br /&gt;    mStaContext.Dispose();&lt;br /&gt; };&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Using the STA Synchronization Context&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let's take another look at our service, now that we have created own ServiceBehavior to apply a custom Synchronization Context&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;[StaServiceBehaviorAttribute]&lt;br /&gt;[ServiceBehavior(UseSynchronizationContext=true, ConcurrencyMode=ConcurrencyMode.Multiple,&lt;br /&gt;  InstanceContextMode=InstanceContextMode.PerCall)]&lt;br /&gt;public class StaService : IStaService&lt;br /&gt;{&lt;br /&gt;  public string DoWorkOnSTAThread(string state)&lt;br /&gt;  {&lt;br /&gt;     ApartmentState aptState = Thread.CurrentThread.GetApartmentState();&lt;br /&gt;     if (aptState == ApartmentState.STA)&lt;br /&gt;        Trace.WriteLine(&amp;quot;Using STA thread&amp;quot;);&lt;br /&gt;&lt;br /&gt;     int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;     Trace.WriteLine(&amp;quot;WCF current thread: &amp;quot; + id);&lt;br /&gt;     //throw new Exception(&amp;quot;boom&amp;quot;);&lt;br /&gt;     return &amp;quot;processed by &amp;quot; + aptState.ToString() + &amp;quot; Thread id: &amp;quot; + id.ToString();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Notice that I kept the WCF service behavior to use PerCall and ConcurrentcyMode.Multiple. Considering we are planning to marshal our code to one STA thread, using ConcurrencyMode.Single will have the same behavior as ConcurrencyMode.Multiple &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Notice I have placed my StaServiceBehaiorAttribue on the service, this will create the STA thread, and apply a STA synchronization context on all the endpoints my service exposes (in the example I only have one endpoint) &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Very well, lets try it, but using the WCF client tool, I have send multiple request to my service and here are the results&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="text"&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;br /&gt;Using STA thread&lt;br /&gt;WCF current thread: 9&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Notice that all the calls to the WCF method are executed on thread 9 &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Notice that thread 9 is a STA thread as we expected &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now I am able to control on which thread the WCF service is executing on.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;A word about hosting&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that using this method you can control the synchronization context of your service no matter what hosting method you choose. If you are hosting using a console application, you could set the synchronization context to STA (using the &lt;code&gt;SynchronizationContext.SetSynchronizationContext&lt;/code&gt;) before opening the host, it will have the same effect.I tried to use a custom &lt;code&gt;ServiceHostFactory&lt;/code&gt; and set the synchronization context there, but it did not work. Let me show you the custom ServiceHostFactory and the custom ServiceHost. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public class StaCustomHostFactory : ServiceHostFactory&lt;br /&gt;   {&lt;br /&gt;      protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)&lt;br /&gt;      {&lt;br /&gt;         return new StaCustomHost(serviceType, baseAddresses);&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public class StaCustomHost : ServiceHost&lt;br /&gt;   {&lt;br /&gt;      public StaCustomHost(Type serviceType, params Uri[] baseAddresses) :&lt;br /&gt;         base(serviceType, baseAddresses)&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      protected override void InitializeRuntime()&lt;br /&gt;      {&lt;br /&gt;         int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;         base.InitializeRuntime();&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      protected override void ApplyConfiguration()&lt;br /&gt;      {&lt;br /&gt;         int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;         // get the configuration from the app.config first&lt;br /&gt;         base.ApplyConfiguration();&lt;br /&gt;&lt;br /&gt;         // create the STA Thread Sync object and attach it to this hosting&lt;br /&gt;         // thread.&lt;br /&gt;         StaSynchronizationContext staContext = new StaSynchronizationContext();&lt;br /&gt;         SynchronizationContext.SetSynchronizationContext(staContext);&lt;br /&gt;      }&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="xml"&gt;&amp;lt;%@ ServiceHost &lt;br /&gt;    Language=&amp;quot;C#&amp;quot; Debug=&amp;quot;true&amp;quot; &lt;br /&gt;    Factory=&amp;quot;StaServiceHost.StaCustomHostFactory&amp;quot; &lt;br /&gt;    Service=&amp;quot;TestStaService.StaService&amp;quot; &lt;br /&gt;    CodeBehind=&amp;quot;StaService.svc.cs&amp;quot; %&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice I set the SynchronizationContext within the ApplyConfiguration method. WCF will take whatever SynchronizationContext is set on the host's thread and use it for each invocation. However it did not work at all. I don't know exactly why, but the only explanation I can come up with is that the code within &lt;code&gt;ApplyConfiguration&lt;/code&gt; does not run within the same thread as the ServiceHost.Open. Considering that the host is opened by webdev or IIS, I really don't know how to set the synchronization context on these threads. Therefore, I recommend you stick to using custom service behavior as I have shown before for overriding the synchronization context of your service's endpoints. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;One little comment about closing the host, as you seen in part II, the STA thread is created as soon as the STA SynchronizationContext object is created. In this case it is created within the service behavior. It is important that this thread ends when the host closes. That's the reason I have coded this event handler: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;void IServiceBehavior.Validate(ServiceDescription serviceDescription,&lt;br /&gt;    System.ServiceModel.ServiceHostBase serviceHostBase)&lt;br /&gt;{&lt;br /&gt; serviceHostBase.Closed += delegate&lt;br /&gt; {&lt;br /&gt;    mStaContext.Dispose();&lt;br /&gt; };&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I have tested this code by stopping the webdev process and placing a break-point on the event handler. I validated that the STA thread is exiting when webdev is closing. Thanks for small WCF miracles. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Is WCF using Send or Post?&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;You might be wondering if the Send or the Post of our sync-context is used. I really didn't know, so I set a breakpoint on both the Send and Post methods, and found out that WCF always uses the Post method. I have changed the service concurency-mode to ConcurrencyMode.Single and still Post was used. So using Single or Multiple concurency, in both cases the Post method is used to marshal code into the STA thread. What about exceptions? Notice I have modified my service to throw an exception: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;   [StaServiceBehaviorAttribute]&lt;br /&gt;   [ServiceBehavior(UseSynchronizationContext=true, ConcurrencyMode=ConcurrencyMode.Multiple,&lt;br /&gt;      InstanceContextMode=InstanceContextMode.PerCall)]&lt;br /&gt;   public class StaService : IStaService&lt;br /&gt;   {&lt;br /&gt;      public string DoWorkOnSTAThread(string state)&lt;br /&gt;      {&lt;br /&gt;         ApartmentState aptState = Thread.CurrentThread.GetApartmentState();&lt;br /&gt;         if (aptState == ApartmentState.STA)&lt;br /&gt;            Trace.WriteLine(&amp;quot;Using STA thread&amp;quot;);&lt;br /&gt;&lt;br /&gt;         int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;         Trace.WriteLine(&amp;quot;WCF current thread: &amp;quot; + id);&lt;br /&gt;         throw new Exception(&amp;quot;boom&amp;quot;);&lt;br /&gt;         //return &amp;quot;processed by &amp;quot; + aptState.ToString() + &amp;quot; Thread id: &amp;quot; + id.ToString();&lt;br /&gt;      }&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Initially, I believed that this might cause the STA thread to terminate, it is an unhandled exception running on the STA thread, but WCF does handle the exception for you. So the STA thread does not end even if you throw exceptions within the STA thread. WCF catches any unhanlded exception and converts them to FaultException on the client thread. This saves our STA thread from ending, so it keeps running regardless if exceptions are thrown. Thank god for another WCF miracle.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;In this article I got into the inner working of WCF and grabbed control on &amp;quot;where&amp;quot; a service method is executed on. I am able to &amp;quot;tell&amp;quot; WCF to marshal all the method calls on a STA thread, allowing us not to worry about calling COM objects that are designed to work on the STA thread. This will also allow you to pop UI within your service method, but I really don't recommend it. By marshaling the code yourself, you can add additional logic to log and validate each invocation. You might even add security at this level and refuse marshaling a call if it does not fit a certain criteria. However, do not use this as a wild card, service side method interception can also do the same thing. Still, now that you know about this feature, you might find a good use for it within your projects.&lt;/p&gt;&lt;br /&gt;Thank you for reading and happy dot netting. &lt;br /&gt;&lt;br /&gt;&lt;ul class="download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://mike.peretz.googlepages.com/STASyncSolution.zip"&gt;Download STASyncSolution.zip - 55.28 KB &lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-3162714721530464343?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/3162714721530464343/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=3162714721530464343' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3162714721530464343'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3162714721530464343'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/12/understanding-synchronizationcontext_29.html' title='Understanding SynchronizationContext Part III'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_cyvneGa_yo8/SVp6QHykpYI/AAAAAAAAFmQ/bWMCB506BOY/s72-c/WCFClient.jpg' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-7726370958585532952</id><published>2008-12-25T19:10:00.000-08:00</published><updated>2008-12-30T11:50:46.817-08:00</updated><title type='text'>Understanding SynchronizationContext Part II</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;In part one I explained the role of SynchronizationContext within the .NET framework 2.0. It is mostly used to allow threads to communicate with the UI thread. We have learned in part one that the SynchronizationContext by itself does nothing to marshal code between threads, in fact this class should of been an abstract class. The .NET framework provided us a version of this class to marshal code into the UI thread, but what about coding your own version of SynchronizationContext to do somthing else. Sounds like a daunting task, but it is really not that bad. I will try to show you in this article how to code your own SynchronizationContext for marshaing code from any thread into a STA thread. In part III of the series I will leverage this class within the WCF framework. But before we start running, we must learn to walk. So lets start.&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;switching work into an STA threads&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;You might be wondering why I am coding this in the first place. STA is a threading model that is used by COM. Long long time ago, before the age of .NET remoting and WCF (sounds like hundred years ago). Developers coded COM classes that can only run on Single Apartment Threads. Why? because the COM runtime would handle thread marshaling for the developer and always made sure that your COM class would execute on the same thread. This way, the COM developer did not need to worry about multi-threading, Mutexes, Semaphores, Events and all the other multi-threading toys out there. Just for the record, COM also provided a Multi Apartment Threading model, for the brave ones. With MTA, the developer had to worry about multi-threading issues but had more control. There is a lot of documentation out there about MTA and STA, all you have to do is google "STA MTA" and read all the history about it. Thank god I don't need to code COM anymore. However, there is a lot of COM out there, and within our company a lot of business logic was coded into COM classes that can only execute on an STA thread. To be able to call these classes from any thread in .NET, I decided to code a custom STA thread synchronization context. After all the sweat and work put into it, it felt right to share it with you, hoping some poor developer out there might find it useful. Although, this article explains how to marshal code into an STA thread, you can take the information in this article and have your own sync context do something else.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;How do we switch between two threads?&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The first question is how would we manage marshaling between two running threads. This problem is typically solved by implementing some sort of a common communication block that both threads can read and write from. An ideal communication object between two threads is a queue.&lt;br /&gt;&lt;br /&gt;A queue provides us the ability to send work from one thread to another based on the invocation order. This is the typical Consumer / Provider model, where one thread plays the role of a consumer (reading from the queue), and another thread plays the role of a provider (writing items to the queue). To simplify things, lets see how this might work:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Thread 1:&lt;/b&gt; Sends a message to a common queue &lt;br&gt;&lt;br /&gt;&lt;b&gt;Thread 2:&lt;/b&gt; Listens for incoming messages from the common queue&lt;br /&gt;&lt;br /&gt;In our case Thread 2 will be an STA thread.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;A closer look at the blocking queue&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;I wanted to have a queue to queue up work items from thread X to my STA thread. I also wanted my thread to dequeue items only when there are items in the queue. If there are no items, I want the dequeue method to wait until something pops into the queue. Typically, this is called a &lt;i&gt;"Blocking Queue"&lt;/i&gt;. Lets see the code: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;internal interface IQueueReader&lt;t&gt; : IDisposable&lt;br /&gt;{&lt;br /&gt;  T Dequeue();&lt;br /&gt;  void ReleaseReader();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal interface IQueueWriter&lt;t&gt; : IDisposable&lt;br /&gt;{&lt;br /&gt;  void Enqueue(T data);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;internal class BlockingQueue&lt;t&gt; : IQueueReader&lt;t&gt;, IQueueWriter&lt;t&gt;, IDisposable&lt;br /&gt;{&lt;br /&gt;  // use a .NET queue to store the data&lt;br /&gt;  private Queue&lt;t&gt; mQueue = new Queue&lt;t&gt;();&lt;br /&gt;  // create a semaphore that contains the items in the queue as resources.&lt;br /&gt;  // initialize the semaphore to zero available resources (empty queue).&lt;br /&gt;  private Semaphore mSemaphore = new Semaphore(0, int.MaxValue);&lt;br /&gt;  // a event that gets triggered when the reader thread is exiting&lt;br /&gt;  private ManualResetEvent mKillThread = new ManualResetEvent(false);&lt;br /&gt;  // wait handles that are used to unblock a Dequeue operation. Either when there is an item in the queue&lt;br /&gt;  // or when the reader thread is exiting.&lt;br /&gt;  private WaitHandle[] mWaitHandles;&lt;br /&gt;&lt;br /&gt;  public BlockingQueue()&lt;br /&gt;  {&lt;br /&gt;    mWaitHandles = new WaitHandle[2] { mSemaphore, mKillThread };&lt;br /&gt;  }&lt;br /&gt;  public void Enqueue(T data)&lt;br /&gt;  {&lt;br /&gt;    lock (mQueue) mQueue.Enqueue(data);&lt;br /&gt;    // add an available resource to the semaphore, because we just put an item&lt;br /&gt;    // into the queue.&lt;br /&gt;    mSemaphore.Release();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public T Dequeue()&lt;br /&gt;  {&lt;br /&gt;    // wait until there is an item in the queue&lt;br /&gt;    WaitHandle.WaitAny(mWaitHandles);&lt;br /&gt;    lock (mQueue)&lt;br /&gt;    {&lt;br /&gt;      if (mQueue.Count &gt; 0)&lt;br /&gt;         return mQueue.Dequeue();&lt;br /&gt;    }&lt;br /&gt;    return default(T);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void ReleaseReader()&lt;br /&gt;  {&lt;br /&gt;    mKillThread.Set();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;  void IDisposable.Dispose()&lt;br /&gt;  {&lt;br /&gt;    if (mSemaphore != null)&lt;br /&gt;    {&lt;br /&gt;      mSemaphore.Close();&lt;br /&gt;      mQueue.Clear();&lt;br /&gt;      mSemaphore = null;&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Because this queue is used by multiple threads, notice that I am blocking access to the queue using the lock statement.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Normally I block the Dequeue method until there is an item in the queue. The way this works is by having a semaphore that represents all the items in the queue as resources. When the semaphore is created for the first time, the queue is empty and therefore there are no resources available, so calling Dequeue will block. (notice there is zero at the first argument indicating no available resources and a large number for the second argument representing the size of the queue.&lt;br /&gt;&lt;code&gt;private Semaphore mSemaphore = new Semaphore(0, int.MaxValue);&lt;/code&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Notice that when I dequeue an item, I block on an array of WaitHandles (&lt;code&gt;WaitHandle.WaitAny(mWaitHandles);)&lt;/code&gt;. This code means &lt;i&gt;"Wait until there is a message, or until the read thread is marked to stop running."&lt;/i&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;I have not shown yet the actual thread, I will show it next. However, the STA thread will be the reading thread, spending most of his time waiting for a message on the queue or processing a message from the queue.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Notice that when a message is enqueued into the queue, it releases the semaphore, indicating that a resource is available, this will cause the dequeue method to unblock.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The semaphore has a max limit of Int.Max, we should never reach anything close to this limit as long as the thread is dequing more of less as fast as it is enqueuing.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;The SendOrPostCallbackItem class&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Notice that the blocking queue class is generic, this was done in case I decide to re-use it in another application (and you are free to use it for your needs as well). So what are we planning to put into this queue? Considering this queue is responsible to marshal code from one thread into another, the ideal item to queue is a delegate. Still, we need a little more then a delegate and not just a simple delegate but a &lt;code&gt;SendOrPostCallback&lt;/code&gt; delegate.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;internal enum ExecutionType&lt;br /&gt;{&lt;br /&gt;   Post,&lt;br /&gt;   Send&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal class SendOrPostCallbackItem&lt;br /&gt;{&lt;br /&gt;   object mState;&lt;br /&gt;   private ExecutionType mExeType;&lt;br /&gt;   SendOrPostCallback mMethod;&lt;br /&gt;   ManualResetEvent mAsyncWaitHandle = new ManualResetEvent(false);&lt;br /&gt;   Exception mException = null;&lt;br /&gt;&lt;br /&gt;   internal SendOrPostCallbackItem(SendOrPostCallback callback,&lt;br /&gt;      object state, ExecutionType type)&lt;br /&gt;   {&lt;br /&gt;      mMethod = callback;&lt;br /&gt;      mState = state;&lt;br /&gt;      mExeType = type;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   internal Exception Exception&lt;br /&gt;   {&lt;br /&gt;      get { return mException; }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   internal bool ExecutedWithException&lt;br /&gt;   {&lt;br /&gt;      get { return mException != null; }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // this code must run ont the STA thread&lt;br /&gt;   internal void Execute()&lt;br /&gt;   {&lt;br /&gt;      if (mExeType == ExecutionType.Send)&lt;br /&gt;         Send();&lt;br /&gt;      else&lt;br /&gt;         Post();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // calling thread will block until mAsyncWaitHandle is set&lt;br /&gt;   internal void Send()&lt;br /&gt;   {&lt;br /&gt;      try&lt;br /&gt;      {&lt;br /&gt;         // call the thread&lt;br /&gt;         mMethod(mState);&lt;br /&gt;      }&lt;br /&gt;      catch (Exception e)&lt;br /&gt;      {&lt;br /&gt;         mException = e;&lt;br /&gt;      }&lt;br /&gt;      finally&lt;br /&gt;      {&lt;br /&gt;         mAsyncWaitHandle.Set();&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   /// &lt;summary&gt;&lt;br /&gt;   /// Unhandled exceptions will terminate the STA thread&lt;br /&gt;   /// &lt;/summary&gt;&lt;br /&gt;   internal void Post()&lt;br /&gt;   {&lt;br /&gt;      mMethod(mState);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   internal WaitHandle ExecutionCompleteWaitHandle&lt;br /&gt;   {&lt;br /&gt;      get { return mAsyncWaitHandle; }&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;SendOrPostCallbackItem contains the delegate we wish to execute on the STA thread.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The Send and Post are really helper methods, they are both responsible for launching the code, and they both designed to be called from the STA thread. However, because the Send is required to block, and to report exceptions back to the calling thread (non-sta thread),I use a ManualResentEvent to single when the execution is complete. I also keep track of the exception, if there is one it will be thrown on the non-sta thread (producer thread)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Post is simple, it just calls the method, no need to notify when it is done and there is no need to track the exception either.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Overall, this class is responsible for two main tasks. Storing the delegate to execute, and executing it in two possible modes. Send and Post, Send requires additional tracking (such as the exception and notification of complication), post just executes the method without doing anything else. Normally, if Post is executed on the STA thread, any exceptions reported by the delegate will cause the thread to end. I will explain this more in part III of the article when I introduce WCF into the mix. But for now, just keep this issue in mind&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;The STA thread and all its glory&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Finally we can show and explain the meat and potatoes of this sync context. Now that we have a queue, and we know what we are planning to push into it, lets look at the STA thread (the thread responsible for marshaling code). &lt;/p&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;internal class StaThread&lt;br /&gt;{&lt;br /&gt;   private Thread mStaThread;&lt;br /&gt;   private IQueueReader&lt;sendorpostcallbackitem&gt; mQueueConsumer;&lt;br /&gt;&lt;br /&gt;   private ManualResetEvent mStopEvent = new ManualResetEvent(false);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   internal StaThread(IQueueReader&lt;sendorpostcallbackitem&gt; reader)&lt;br /&gt;   {&lt;br /&gt;      mQueueConsumer = reader;&lt;br /&gt;      mStaThread = new Thread(Run);&lt;br /&gt;      mStaThread.Name = "STA Worker Thread";&lt;br /&gt;      mStaThread.SetApartmentState(ApartmentState.STA);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   internal void Start()&lt;br /&gt;   {&lt;br /&gt;      mStaThread.Start();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   internal void Join()&lt;br /&gt;   {&lt;br /&gt;      mStaThread.Join();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   private void Run()&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      while (true)&lt;br /&gt;      {&lt;br /&gt;         bool stop = mStopEvent.WaitOne(0);&lt;br /&gt;         if (stop)&lt;br /&gt;         {&lt;br /&gt;            break;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;        SendOrPostCallbackItem workItem = mQueueConsumer.Dequeue();&lt;br /&gt;        if (workItem != null)&lt;br /&gt;            workItem.Execute();&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   internal void Stop()&lt;br /&gt;   {&lt;br /&gt;      mStopEvent.Set();&lt;br /&gt;      mQueueConsumer.ReleaseReader();&lt;br /&gt;      mStaThread.Join();&lt;br /&gt;      mQueueConsumer.Dispose();&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;One of the most important parts of this class is in the constructor, so lets take a look at it again &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;internal StaThread(IQueueReader&lt;sendorpostcallbackitem&gt; reader)&lt;br /&gt;{&lt;br /&gt;   mQueueConsumer = reader;&lt;br /&gt;   mStaThread = new Thread(Run);&lt;br /&gt;   mStaThread.Name = "STA Worker Thread";&lt;br /&gt;   mStaThread.SetApartmentState(ApartmentState.STA);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;This class takes an interface of type IQueueReader, this is really our blocking queue. the reason I decided to put an interface here, is because this thread is a reading thread, and should not have access to writing methods&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The thread is being setup as a STA thread, giving the thread a name helps when debugging using the thread output window.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Notice the thread is not started yet. A method called Start will start the thread, and this will happen within our StaSynchronizationContext class which I will show soon.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Lets take a look at the Run method. The run method represents our STA thread. Its main job is to dequeue items from our blocking queue and execute them. Executing any work items on the Run method means executing them on the STA thread. Therefore, it doesn't really matter which thread has placed them in the queue, what's important is that items are read within the STA thread, and executed in the STA thread. If you think about this, this is in fact thread marshalling in action.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;private void Run()&lt;br /&gt;{&lt;br /&gt;   while (true)&lt;br /&gt;   {&lt;br /&gt;      bool stop = mStopEvent.WaitOne(0);&lt;br /&gt;      if (stop)&lt;br /&gt;      {&lt;br /&gt;         break;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;     SendOrPostCallbackItem workItem = mQueueConsumer.Dequeue();&lt;br /&gt;     if (workItem != null)&lt;br /&gt;         workItem.Execute();&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I tried to keep the Run method as simple as possible, but lets stress out a few points.&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The STA thread is running all the time, so I have made a while(true) loop. Normally, I am not a fan of this type of loop, but I wanted the reader of the code to understand, this thread is not suppose to go down unless the context class is disposed. A while(true) sends this type of message.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;mStopEvent is a ManualResetEvent, it is signaled when the STA thread is marked to stop running. When the Stop() method is called, the mStopEvent is set, causing the main loop to exit. The Stop method also releases any waiting Dequeue operation by marking the queue to stop processing messages.&lt;br /&gt;&lt;li&gt;&lt;code&gt;mQueueConsumer.Dequeue()&lt;/code&gt; is responsible for reading work items from the queue. This method will block until a work item is in the queue.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;When a work-item is dequeued, the work-item is executed. Execute() if you remember will execute the code in the delegate associated with the work item. It is during this Execute method that the code is marshaled on the STA thread.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;Creating the STA Synchronization Context class&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We almost have all the pieces we need to have our STA Sync Context running. We got a work item that contains our delegate to execute on the STA thread. We got a nice little blocking queue to handle communication between the STA thread and any other thread. We even have our little STA Run method always looking at our queue, pumping messages out of it and running any work items that are fetched. The only thing we are missing now is the actual Synchronization Context class itself. So lets see it and go over the code in detail...&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;StaSynchronizationContext.cs&lt;/h3&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;public class StaSynchronizationContext : SynchronizationContext, IDisposable&lt;br /&gt;{&lt;br /&gt;   private BlockingQueue&lt;sendorpostcallbackitem&gt; mQueue;&lt;br /&gt;   private StaThread mStaThread;&lt;br /&gt;   public StaSynchronizationContext()&lt;br /&gt;      : base()&lt;br /&gt;   {&lt;br /&gt;      mQueue = new BlockingQueue&lt;sendorpostcallbackitem&gt;();&lt;br /&gt;      mStaThread = new StaThread(mQueue);&lt;br /&gt;      mStaThread.Start();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public override void Send(SendOrPostCallback d, object state)&lt;br /&gt;   {&lt;br /&gt;      // create an item for execution&lt;br /&gt;      SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state, ExecutionType.Send);&lt;br /&gt;      // queue the item&lt;br /&gt;      mQueue.Enqueue(item);&lt;br /&gt;      // wait for the item execution to end&lt;br /&gt;      item.ExecutionCompleteWaitHandle.WaitOne();&lt;br /&gt;&lt;br /&gt;      // if there was an exception, throw it on the caller thread, not the&lt;br /&gt;      // sta thread.&lt;br /&gt;      if (item.ExecutedWithException)&lt;br /&gt;         throw item.Exception;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public override void Post(SendOrPostCallback d, object state)&lt;br /&gt;   {&lt;br /&gt;      // queue the item and don't wait for its execution. This is risky because&lt;br /&gt;      // an unhandled exception will terminate the STA thread. Use with caution.&lt;br /&gt;      SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state, ExecutionType.Post);&lt;br /&gt;      mQueue.Enqueue(item);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void Dispose()&lt;br /&gt;   {&lt;br /&gt;      mStaThread.Stop();&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public override SynchronizationContext CreateCopy()&lt;br /&gt;   {&lt;br /&gt;      return this;&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This is really the class that uses all the other classes I have showed before. I have named it the StaSynchronizationContext because it is responsible to marshal code into an STA thread, allowing the caller to execute COM APIs that must be on an STA thread. Lets look a the Send API which is responsible for sending work on the STA thread. Notice this class inherits from &lt;code&gt;SynchronizationContext&lt;/code&gt;, but overrides the default Send and Post methods.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;public override void Send(SendOrPostCallback d, object state)&lt;br /&gt;{&lt;br /&gt;   // create an item for execution&lt;br /&gt;   SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state, ExecutionType.Send);&lt;br /&gt;   // queue the item&lt;br /&gt;   mQueue.Enqueue(item);&lt;br /&gt;   // wait for the item execution to end&lt;br /&gt;   item.ExecutionCompleteWaitHandle.WaitOne();&lt;br /&gt;&lt;br /&gt;   // if there was an exception, throw it on the caller thread, not the&lt;br /&gt;   // sta thread.&lt;br /&gt;   if (item.ExecutedWithException)&lt;br /&gt;      throw item.Exception;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that the send operation is a blocking operation, this means we block until the operation on the STA thread is complete. Remember we have placed a ManualReset event on the SendOrPostCallbackItem class, so we know when the execution is done. We are also trapping and caching any exceptions within SendOrPostCallbackItem so we can throw them on the calling thread and not on the STA thread. The Post on the other hand is not a waiting call, so all we do is queue the item and we are not waiting for the delegate execution to finish.&lt;br /&gt;&lt;br /&gt;&lt;p&gt;That's it, we now have a SynchronizationContext that will marshal code between any thread into a single STA thread. In my case, this will allow me to execute COM APIs within my STA thread, so COM classes can feel at home, as if they are running in VB6. To actually test this class, I have created a test program, here is the code&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;   public class Params&lt;br /&gt;   {&lt;br /&gt;      public string Output {get; set;}&lt;br /&gt;      public int CallCounter { get; set; }&lt;br /&gt;      public int OriginalThread { get; set; }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   class Program&lt;br /&gt;   {&lt;br /&gt;      private static int mCount = 0;&lt;br /&gt;      private static StaSynchronizationContext mStaSyncContext = null;&lt;br /&gt;      static void Main(string[] args)&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mStaSyncContext = new StaSynchronizationContext();&lt;br /&gt;         for (int i = 0; i &lt; 100; i++)&lt;br /&gt;         {&lt;br /&gt;            ThreadPool.QueueUserWorkItem(NonStaThread);&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;         Console.WriteLine("Processing");&lt;br /&gt;         Console.WriteLine("Press any key to dispose SyncContext");&lt;br /&gt;         Console.ReadLine();&lt;br /&gt;         mStaSyncContext.Dispose();&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      private static void NonStaThread(object state)&lt;br /&gt;      {&lt;br /&gt;         int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;&lt;br /&gt;         for (int i = 0; i &lt; 10; i++)&lt;br /&gt;         {&lt;br /&gt;            var param = new Params { OriginalThread = id, CallCounter = i };&lt;br /&gt;            mStaSyncContext.Send(RunOnStaThread, param);&lt;br /&gt;            Debug.Assert(param.Output == "Processed", "Unexpected behavior by STA thread");&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      private static void RunOnStaThread(object state)&lt;br /&gt;      {&lt;br /&gt;         mCount++;&lt;br /&gt;         Console.WriteLine(mCount);&lt;br /&gt;         int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;         var args = (Params)state;&lt;br /&gt;         Trace.WriteLine("STA id " + id + " original thread " + args.OriginalThread + " call count " + args.CallCounter);&lt;br /&gt;         args.Output = "Processed";&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The test program will create a number of threads using the thread pool. These thread pool threads then use the StaSynchronizationContext to execute the code within the method RunOnStaThread. Running this test program, I have blasted the STA thread from 100 .NET threads, each thread marshaling the code RunOnStaThread 10 times. Notice that the STA thread ID will always be the same. Notice the results below, the STA thread is always 11, and calls are coming from multiple threads (I have shrunk the output)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="text"&gt;&lt;br /&gt;STA id 11 original thread 7 call count 0&lt;br /&gt;STA id 11 original thread 12 call count 0&lt;br /&gt;STA id 11 original thread 7 call count 1&lt;br /&gt;STA id 11 original thread 12 call count 1&lt;br /&gt;STA id 11 original thread 7 call count 2&lt;br /&gt;STA id 11 original thread 12 call count 2&lt;br /&gt;STA id 11 original thread 7 call count 3&lt;br /&gt;STA id 11 original thread 12 call count 3&lt;br /&gt;STA id 11 original thread 7 call count 4&lt;br /&gt;STA id 11 original thread 12 call count 4&lt;br /&gt;STA id 11 original thread 7 call count 5&lt;br /&gt;STA id 11 original thread 12 call count 5&lt;br /&gt;STA id 11 original thread 7 call count 6&lt;br /&gt;STA id 11 original thread 12 call count 6&lt;br /&gt;STA id 11 original thread 7 call count 7&lt;br /&gt;STA id 11 original thread 12 call count 7&lt;br /&gt;STA id 11 original thread 7 call count 8&lt;br /&gt;STA id 11 original thread 12 call count 8&lt;br /&gt;STA id 11 original thread 7 call count 9&lt;br /&gt;STA id 11 original thread 12 call count 9&lt;br /&gt;STA id 11 original thread 7 call count 0&lt;br /&gt;STA id 11 original thread 12 call count 0&lt;br /&gt;STA id 11 original thread 7 call count 1&lt;br /&gt;STA id 11 original thread 12 call count 1&lt;br /&gt;STA id 11 original thread 7 call count 2&lt;br /&gt;STA id 11 original thread 12 call count 2&lt;br /&gt;STA id 11 original thread 7 call count 3&lt;br /&gt;STA id 11 original thread 12 call count 3&lt;br /&gt;STA id 11 original thread 7 call count 4&lt;br /&gt;STA id 11 original thread 12 call count 4&lt;br /&gt;STA id 11 original thread 7 call count 5&lt;br /&gt;STA id 11 original thread 12 call count 5&lt;br /&gt;STA id 11 original thread 7 call count 6&lt;br /&gt;STA id 11 original thread 12 call count 6&lt;br /&gt;STA id 11 original thread 7 call count 7&lt;br /&gt;STA id 11 original thread 12 call count 7&lt;br /&gt;STA id 11 original thread 7 call count 8&lt;br /&gt;STA id 11 original thread 12 call count 8&lt;br /&gt;STA id 11 original thread 7 call count 9&lt;br /&gt;STA id 11 original thread 12 call count 9&lt;br /&gt;STA id 11 original thread 7 call count 0&lt;br /&gt;STA id 11 original thread 12 call count 0&lt;br /&gt;STA id 11 original thread 7 call count 1&lt;br /&gt;STA id 11 original thread 12 call count 1&lt;br /&gt;STA id 11 original thread 7 call count 2&lt;br /&gt;STA id 11 original thread 12 call count 2&lt;br /&gt;STA id 11 original thread 7 call count 3&lt;br /&gt;STA id 11 original thread 12 call count 3&lt;br /&gt;STA id 11 original thread 7 call count 4&lt;br /&gt;STA id 11 original thread 12 call count 4&lt;br /&gt;STA id 11 original thread 7 call count 5&lt;br /&gt;STA id 11 original thread 12 call count 5&lt;br /&gt;STA id 11 original thread 7 call count 6&lt;br /&gt;STA id 11 original thread 12 call count 6&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Wait a minute, I can do the same thing without using a SynchronizationContext, so why bother?&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;True, there is really no need to build a synchronization context to marshal code into another thread. I could of just used my queue and the STA thread to do all the work directly within my code. Its nice that I am playing by the rules of .NET and I provide my own implementation, so others can use it, but really it is not required. So why bother? The reason is because of WCF. WCF allows you to provide a SynchronizationContext for the execution of operations within a service. This is a very powerful feature of WCF that is normally used to marshal WCF service calls into the UI thread. However, in my case, because I played nice and I created a SynchronizationContext class and not just any class, I can now tell WCF to execute all my service methods on an STA thread. This was the main reason for writing the series on this class.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;This article shows that you can create your own version of a SynchronizationContext class. I have showed that a Blocking Queue is a good candidate for communication between threads. We successfuly marshalled code from any thread into a single STA thread. Now that we have our Synchronization Context class, we can put it to work within a WCF service. This will be the main focus on the 3ed part of the series. Once you understand how to build your own Synchronization Context and apply it to a WCF service, you are in control of "where" your code is running when a WCF method is executed - a very powerful feature within a very powerful WCF framework.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;For those of you that want the code. I will provide a full VS2008 solution within the 3ed part of the articles&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-7726370958585532952?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/7726370958585532952/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=7726370958585532952' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/7726370958585532952'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/7726370958585532952'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/12/understanding-synchronizationcontext.html' title='Understanding SynchronizationContext Part II'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-3801031245129875956</id><published>2008-12-21T21:26:00.000-08:00</published><updated>2008-12-25T12:21:19.347-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Threading'/><category scheme='http://www.blogger.com/atom/ns#' term='SyncrhronizationContext'/><title type='text'>Understanding SyncrhronizationContext</title><content type='html'>&lt;hr class="Divider subdue"&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;span id="ArticleContent"&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;SynchronizationContext - MSDN lets you down&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I don't know why, but there is really not much information about this new class within the .NET framework. The MSDN documentation contains very little information on how to use &lt;code&gt;SynchronizationContext&lt;/code&gt;. Initially, I must say that I had a hard time understanding the reason for this new class and how to use it. After reading a lot on the subject, I finally understood the purpose of this class and how it should be used. I decided to write this article to help other developers understand how to use this class, and what it can and can not do for you. (&lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"&gt;MSDN&lt;/a&gt;)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Using SyncrhronizationContext to Marshal Code from One Thread to Another&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let's get some technical points out of the way so we can show how to use this class. A &lt;code&gt;SyncrhronizationContext&lt;/code&gt; allows a thread to communicate with another thread. Suppose you have two threads, &lt;code&gt;Thread1&lt;/code&gt; and &lt;code&gt;Thread2&lt;/code&gt;. Say, &lt;code&gt;Thread1&lt;/code&gt; is doing some work, and then &lt;code&gt;Thread1&lt;/code&gt; wishes to execute code on &lt;code&gt;Thread2&lt;/code&gt;. One possible way to do it is to ask &lt;code&gt;Thread2&lt;/code&gt; for its &lt;code&gt;SyncrhronizationContext&lt;/code&gt; object, give it to &lt;code&gt;Thread1&lt;/code&gt;, and then &lt;code&gt;Thread1&lt;/code&gt; can call &lt;code&gt;SyncrhronizationContext.Send&lt;/code&gt; to execute the code on &lt;code&gt;Thread2&lt;/code&gt;. Sounds like magic... Well, there is a something you should know. Not every thread has a &lt;code&gt;SyncrhronizationContext&lt;/code&gt; attached to it. One thread that always has a &lt;code&gt;SyncrhronizationContext&lt;/code&gt; is the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Who puts the &lt;code&gt;SyncrhronizationContext&lt;/code&gt; into the UI thread? Any guesses? Give up? OK, here it is, the first control that is created on the thread places the &lt;code&gt;SyncrhronizationContext&lt;/code&gt; into that thread. Normally, it is the first form that gets created. How do I know? Well, I tried it out.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Because my code uses &lt;code&gt;SynchronizationContext.Current&lt;/code&gt;, let me explain what this static property gives us. &lt;code&gt;SynchronizationContext.Current&lt;/code&gt; allows us to get a &lt;code&gt;SynchronizationContext&lt;/code&gt; that is attached to the current thread. Let's be clear here, &lt;code&gt;SynchronizationContext.Current&lt;/code&gt; is not a singleton per AppDomain, but per thread. This means that two threads can have different instances of &lt;code&gt;SynchronizationContext&lt;/code&gt; when calling &lt;code&gt;SynchronizationContext.Current&lt;/code&gt;. If you wonder where the actual context is stored, it is stored within the Thread data store (and as I said before, not in the global memory space of the appdomain).&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;OK, let's look at the code that places a SynchronizationContext within our UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;[STAThread]&lt;br /&gt;static void Main()&lt;br /&gt;{&lt;br /&gt;Application.EnableVisualStyles();&lt;br /&gt;Application.SetCompatibleTextRenderingDefault(false);&lt;br /&gt;// lets check the context here&lt;br /&gt;var context = SynchronizationContext.Current;&lt;br /&gt;if (context == null)&lt;br /&gt;MessageBox.Show("No context for this thread");&lt;br /&gt;else&lt;br /&gt;MessageBox.Show("We got a context");&lt;br /&gt;&lt;br /&gt;// create a form&lt;br /&gt;Form1 form = new Form1();&lt;br /&gt;// lets check it again after creating a form&lt;br /&gt;context = SynchronizationContext.Current;&lt;br /&gt;if (context == null)&lt;br /&gt;MessageBox.Show("No context for this thread");&lt;br /&gt;else&lt;br /&gt;MessageBox.Show("We got a context");&lt;br /&gt;&lt;br /&gt;if (context == null)&lt;br /&gt;MessageBox.Show("No context for this thread");&lt;br /&gt;&lt;br /&gt;Application.Run(new Form1());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;As you can see, there are a few points to note:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The first message box will indicate that there is no context attached to the thread. That's because .NET doesn't even know what is going to happen on this thread, and there is no runtime class that initializes the Sync Context for this thread.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Right after creating the form, notice that the context is set. The &lt;code&gt;Form&lt;/code&gt; class is responsible for this. It checks if a Sync Context is present, and if it is not, it places it there. Remember that the context is always the same on the same thread, so any UI control can access it. This is because all UI operations must be running on the UI thread. To be more specific, the thread that creates the window is the thread that can communicate with the window. In our case, it is the main thread of the application.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;How do I use it?&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now that the UI thread is nice enough to give us a Sync Context so we can "run code" under the UI thread, how do we use it?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;First, do we really have to marshal code into the UI thread? Yes. If you are running on a thread other than the UI thread, you can not update the UI. Want to be a hero and try it? You will get an exception (in version 1.0, they didn't enforce the exception, it just crashed the application, but in version 2.0, there is a fat ugly exception that pops in your face).&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To be fair, I will say that you don't have to use this class to sync into the UI thread. You can use the &lt;code&gt;InvokeRequired&lt;/code&gt; property (which is on every UI control class) and see if you need to marshal your code. If you get a "&lt;code lang="cs"&gt;true&lt;/code&gt;" out of &lt;code&gt;InvokeRequired&lt;/code&gt;, then you have to use &lt;code&gt;Control.Invoke&lt;/code&gt; to marshal the code to the UI thread. Great! Why keep reading? Well, there is an issue with this technique. You must have a &lt;code&gt;Control&lt;/code&gt; in order to call &lt;code&gt;Invoke&lt;/code&gt; on it. It doesn't matter which UI control, but you need at least one control reference available to you within your non-UI thread in order to do this type of thread marshalling. From a design prospective, you never want to have a UI reference within your BI layer. So, you can leave all sync operations on the UI class, and make sure the UI is responsible to marshal its own work (see my article on the MVP pattern). However, this puts more responsibility on the UI, and makes the UI smarter than we want it to be, I must say. It would be nice for the BI to have the ability to marshal code to the UI thread without having a reference to a control or a form.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So, how is it done?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Simple. Create a thread, sent it the sync context, and have this thread use the sync object to marshal code into the UI thread. Let's see an example:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;In the following example, I have a list box that is populated from a worker thread. The thread simulates a computation and then writes to the UI list box. The thread used to update the UI is launched from the &lt;code&gt;mToolStripButtonThreads_Click&lt;/code&gt; event handler.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;First, let's see what's on the form:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt; private void InitializeComponent()&lt;br /&gt;{&lt;br /&gt;System.ComponentModel.ComponentResourceManager resources =&lt;br /&gt;new System.ComponentModel.ComponentResourceManager(typeof(Form1));&lt;br /&gt;this.mListBox = new System.Windows.Forms.ListBox();&lt;br /&gt;this.toolStrip1 = new System.Windows.Forms.ToolStrip();&lt;br /&gt;this.mToolStripButtonThreads = new System.Windows.Forms.ToolStripButton();&lt;br /&gt;this.toolStrip1.SuspendLayout();&lt;br /&gt;this.SuspendLayout();&lt;br /&gt;//&lt;br /&gt;// mListBox&lt;br /&gt;//&lt;br /&gt;this.mListBox.Dock = System.Windows.Forms.DockStyle.Fill;&lt;br /&gt;this.mListBox.FormattingEnabled = true;&lt;br /&gt;this.mListBox.Location = new System.Drawing.Point(0, 0);&lt;br /&gt;this.mListBox.Name = "mListBox";&lt;br /&gt;this.mListBox.Size = new System.Drawing.Size(284, 264);&lt;br /&gt;this.mListBox.TabIndex = 0;&lt;br /&gt;//&lt;br /&gt;// toolStrip1&lt;br /&gt;//&lt;br /&gt;this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {&lt;br /&gt;this.mToolStripButtonThreads});&lt;br /&gt;this.toolStrip1.Location = new System.Drawing.Point(0, 0);&lt;br /&gt;this.toolStrip1.Name = "toolStrip1";&lt;br /&gt;this.toolStrip1.Size = new System.Drawing.Size(284, 25);&lt;br /&gt;this.toolStrip1.TabIndex = 1;&lt;br /&gt;this.toolStrip1.Text = "toolStrip1";&lt;br /&gt;//&lt;br /&gt;// mToolStripButtonThreads&lt;br /&gt;//&lt;br /&gt;this.mToolStripButtonThreads.DisplayStyle =&lt;br /&gt;System.Windows.Forms.ToolStripItemDisplayStyle.Text;&lt;br /&gt;this.mToolStripButtonThreads.Image = ((System.Drawing.Image)&lt;br /&gt;(resources.GetObject("mToolStripButtonThreads.Image")));&lt;br /&gt;this.mToolStripButtonThreads.ImageTransparentColor =&lt;br /&gt;System.Drawing.Color.Magenta;&lt;br /&gt;this.mToolStripButtonThreads.Name = "mToolStripButtonThreads";&lt;br /&gt;this.mToolStripButtonThreads.Size = new System.Drawing.Size(148, 22);&lt;br /&gt;this.mToolStripButtonThreads.Text = "Press Here to start threads";&lt;br /&gt;this.mToolStripButtonThreads.Click +=&lt;br /&gt;new System.EventHandler(this.mToolStripButtonThreads_Click);&lt;br /&gt;//&lt;br /&gt;// Form1&lt;br /&gt;//&lt;br /&gt;this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);&lt;br /&gt;this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;&lt;br /&gt;this.ClientSize = new System.Drawing.Size(284, 264);&lt;br /&gt;this.Controls.Add(this.toolStrip1);&lt;br /&gt;this.Controls.Add(this.mListBox);&lt;br /&gt;this.Name = "Form1";&lt;br /&gt;this.Text = "Form1";&lt;br /&gt;this.toolStrip1.ResumeLayout(false);&lt;br /&gt;this.toolStrip1.PerformLayout();&lt;br /&gt;this.ResumeLayout(false);&lt;br /&gt;this.PerformLayout();&lt;br /&gt;}&lt;br /&gt;#endregion&lt;br /&gt;private System.Windows.Forms.ListBox mListBox;&lt;br /&gt;private System.Windows.Forms.ToolStrip toolStrip1;&lt;br /&gt;private System.Windows.Forms.ToolStripButton mToolStripButtonThreads;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now, let's see the example:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public partial class Form1 : Form&lt;br /&gt;{&lt;br /&gt;public Form1()&lt;br /&gt;{&lt;br /&gt;InitializeComponent();&lt;br /&gt;}&lt;br /&gt;private void mToolStripButtonThreads_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;// lets see the thread id&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("mToolStripButtonThreads_Click thread: " + id);&lt;br /&gt;// grab the sync context associated to this&lt;br /&gt;// thread (the UI thread), and save it in uiContext&lt;br /&gt;// note that this context is set by the UI thread&lt;br /&gt;// during Form creation (outside of your control)&lt;br /&gt;// also note, that not every thread has a sync context attached to it.&lt;br /&gt;SynchronizationContext uiContext = SynchronizationContext.Current;&lt;br /&gt;// create a thread and associate it to the run method&lt;br /&gt;Thread thread = new Thread(Run);&lt;br /&gt;// start the thread, and pass it the UI context,&lt;br /&gt;// so this thread will be able to update the ui&lt;br /&gt;// from within the thread&lt;br /&gt;thread.Start(uiContext);&lt;br /&gt;}&lt;br /&gt;private void Run(object state)&lt;br /&gt;{&lt;br /&gt;// lets see the thread id&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("Run thread: " + id);&lt;br /&gt;// grab the context from the state&lt;br /&gt;SynchronizationContext uiContext = state as SynchronizationContext;&lt;br /&gt;for (int i = 0; i &amp;lt; 1000; i++)&lt;br /&gt;{&lt;br /&gt;// normally you would do some code here&lt;br /&gt;// to grab items from the database. or some long&lt;br /&gt;// computation&lt;br /&gt;Thread.Sleep(10);&lt;br /&gt;// use the ui context to execute the UpdateUI method,&lt;br /&gt;// this insure that the UpdateUI method will run on the UI thread.&lt;br /&gt;uiContext.Post(UpdateUI, "line " + i.ToString());&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;/// &amp;lt;summary&amp;gt;&lt;br /&gt;/// This method is executed on the main UI thread.&lt;br /&gt;/// &amp;lt;/summary&amp;gt;&lt;br /&gt;private void UpdateUI(object state)&lt;br /&gt;{&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("UpdateUI thread:" + id);&lt;br /&gt;string text = state as string;&lt;br /&gt;mListBox.Items.Add(text);&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let's go over this code. Notice that I log the thread ID of each method so we can review it later.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;For example:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;// lets see the thread id&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("mToolStripButtonThreads_Click thread: " + id);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;When pressing on the toolstrip button, a thread is launched with its delegate pointing to the &lt;code&gt;Run&lt;/code&gt; method. However, notice that I am passing state to this thread. I am passing the Sync Context of the UI thread by calling &lt;code&gt;SynchronizationContext uiContext = SynchronizationContext.Current;&lt;/code&gt;. Because I am running on the event handler thread of the toolstrip button, I know I am currently running on the UI thread, and by calling &lt;code&gt;SynchronizationContext.Current&lt;/code&gt;, I will get the sync context for the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;code&gt;Run&lt;/code&gt; will first grab the &lt;code&gt;SynchronizationContext&lt;/code&gt; from its state, so it can have the knowledge of how to marshal code into the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;// grab the context from the state&lt;br /&gt;SynchronizationContext uiContext = state as SynchronizationContext;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The &lt;code&gt;Run&lt;/code&gt; thread writes 1000 lines into the list box. How? Well, first it uses the &lt;code&gt;Send&lt;/code&gt; method on the &lt;code&gt;SynchronizationContext&lt;/code&gt;:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public virtual void Send(SendOrPostCallback d, object state);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Calling &lt;code&gt;SynchronizationContext.Send&lt;/code&gt; takes two arguments, a delegate pointing to a method and a state object. Within our example &lt;code&gt;uiContext.Send(UpdateUI, "line " + i.ToString());&lt;/code&gt;, &lt;code&gt;UpdateUI&lt;/code&gt; is the value we provide for the delegate, and &lt;code&gt;state&lt;/code&gt; contains the string we want to add to the listbox. The code in &lt;code&gt;UpdateUI&lt;/code&gt; is supposed to run on the UI thread, and not on the calling thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;private void UpdateUI(object state)&lt;br /&gt;{&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("UpdateUI thread:" + id);&lt;br /&gt;string text = state as string;&lt;br /&gt;mListBox.Items.Add(text);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that this code directly runs on the UI thread. There is no checking for &lt;code&gt;InvokerRequired&lt;/code&gt; because I know it is on the UI thread due to the fact that it was used with the &lt;code&gt;Send&lt;/code&gt; method of the UI &lt;code&gt;SynchronizationContext&lt;/code&gt;.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let's look at the thread IDs and see if it makes sense:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="text"&gt;mToolStripButtonThreads_Click thread: 10&lt;br /&gt;Run thread: 3&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;UpdateUI thread:10&lt;br /&gt;... (x1000 times)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This means that the UI thread is 10, the worker thread (&lt;code&gt;Run&lt;/code&gt;) is 3, and when we update the UI, notice we are on thread ID 10 again (the UI thread). So, everything is working as advertised.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Error Handling&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Very nice, we are able to marshal code into the UI thread, but what happens when the code we marshal throws an exception? Who is responsible to catch it? The UI thread or the worker thread?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;private void Run(object state)&lt;br /&gt;{&lt;br /&gt;// lets see the thread id&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Trace.WriteLine("Run thread: " + id);&lt;br /&gt;// grab the context from the state&lt;br /&gt;SynchronizationContext uiContext = state as SynchronizationContext;&lt;br /&gt;for (int i = 0; i &amp;lt; 1000; i++)&lt;br /&gt;{&lt;br /&gt;Trace.WriteLine("Loop " + i.ToString());&lt;br /&gt;// normally you would do some code here&lt;br /&gt;// to grab items from the database. or some long&lt;br /&gt;// computation&lt;br /&gt;Thread.Sleep(10);&lt;br /&gt;// use the ui context to execute the UpdateUI method, this insure that the&lt;br /&gt;// UpdateUI method will run on the UI thread.&lt;br /&gt;try&lt;br /&gt;{&lt;br /&gt;uiContext.Send(UpdateUI, "line " + i.ToString());&lt;br /&gt;}&lt;br /&gt;catch (Exception e)&lt;br /&gt;{&lt;br /&gt;Trace.WriteLine(e.Message);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;/// &amp;lt;summary&amp;gt;&lt;br /&gt;/// This method is executed on the main UI thread.&lt;br /&gt;/// &amp;lt;/summary&amp;gt;&lt;br /&gt;private void UpdateUI(object state)&lt;br /&gt;{&lt;br /&gt;throw new Exception("Boom");&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I modified the code so that the &lt;code&gt;UpdateUI&lt;/code&gt; method throws an exception &lt;code lang="cs"&gt;throw new Exception("Boom");&lt;/code&gt;. Also, I have modified the &lt;code&gt;Run&lt;/code&gt; method to place a &lt;code lang="cs"&gt;try/catch&lt;/code&gt; around the &lt;code&gt;Send&lt;/code&gt; method.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;try&lt;br /&gt;{&lt;br /&gt;uiContext.Send(UpdateUI, "line " + i.ToString());&lt;br /&gt;}&lt;br /&gt;catch (Exception e)&lt;br /&gt;{&lt;br /&gt;Trace.WriteLine(e.Message);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;When running this code, I noticed that the exception is caught in the Run thread and not on the UI thread. This is interesting because you might expect the exception to bring down the UI thread, considering no class is catching the exception on the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Therefore, the &lt;code&gt;Send&lt;/code&gt; method is doing a little magic; it is executing our code in a blocking fashion, and it reports back any exception during its execution.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Send vs. Post&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Using &lt;code&gt;Send&lt;/code&gt; is only one of two possible methods you can use to marshal code on the UI thread. There is another method called &lt;code&gt;Post&lt;/code&gt;. What's the difference? A lot!&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Maybe it is time to see this class in more detail, so let's review the interface of &lt;code&gt;SynchronizationContext&lt;/code&gt;:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;// Summary:&lt;br /&gt;// Provides the basic functionality for propagating a synchronization context&lt;br /&gt;// in various synchronization models.&lt;br /&gt;public class SynchronizationContext&lt;br /&gt;{&lt;br /&gt;// Summary:&lt;br /&gt;// Creates a new instance of the System.Threading.SynchronizationContext class.&lt;br /&gt;public SynchronizationContext();&lt;br /&gt;// Summary:&lt;br /&gt;// Gets the synchronization context for the current thread.&lt;br /&gt;//&lt;br /&gt;// Returns:&lt;br /&gt;// A System.Threading.SynchronizationContext object representing the current&lt;br /&gt;// synchronization context.&lt;br /&gt;public static SynchronizationContext Current { get; }&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, creates a copy of the synchronization&lt;br /&gt;// context.&lt;br /&gt;//&lt;br /&gt;// Returns:&lt;br /&gt;// A new System.Threading.SynchronizationContext object.&lt;br /&gt;public virtual SynchronizationContext CreateCopy();&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// Determines if wait notification is required.&lt;br /&gt;//&lt;br /&gt;// Returns:&lt;br /&gt;// true if wait notification is required; otherwise, false.&lt;br /&gt;public bool IsWaitNotificationRequired();&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, responds to the notification that an&lt;br /&gt;// operation has completed.&lt;br /&gt;public virtual void OperationCompleted();&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, responds to the notification that an&lt;br /&gt;// operation has started.&lt;br /&gt;public virtual void OperationStarted();&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, dispatches an asynchronous message to&lt;br /&gt;// a synchronization context.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// d:&lt;br /&gt;// The System.Threading.SendOrPostCallback delegate to call.&lt;br /&gt;//&lt;br /&gt;// state:&lt;br /&gt;// The object passed to the delegate.&lt;br /&gt;public virtual void Post(SendOrPostCallback d, object state);&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, dispatches a synchronous message to a&lt;br /&gt;// synchronization context.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// d:&lt;br /&gt;// The System.Threading.SendOrPostCallback delegate to call.&lt;br /&gt;//&lt;br /&gt;// state:&lt;br /&gt;// The object passed to the delegate.&lt;br /&gt;public virtual void Send(SendOrPostCallback d, object state);&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// Sets the current synchronization context.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// syncContext:&lt;br /&gt;// The System.Threading.SynchronizationContext object to be set.&lt;br /&gt;public static void SetSynchronizationContext(SynchronizationContext syncContext);&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// Sets notification that wait notification is required and prepares the callback&lt;br /&gt;// method so it can be called more reliably when a wait occurs.&lt;br /&gt;protected void SetWaitNotificationRequired();&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// Waits for any or all the elements in the specified array to receive a signal.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// waitHandles:&lt;br /&gt;// An array of type System.IntPtr that contains the native operating system&lt;br /&gt;// handles.&lt;br /&gt;//&lt;br /&gt;// waitAll:&lt;br /&gt;// true to wait for all handles; false to wait for any handle.&lt;br /&gt;//&lt;br /&gt;// millisecondsTimeout:&lt;br /&gt;// The number of milliseconds to wait, or System.Threading.Timeout.Infinite&lt;br /&gt;// (-1) to wait indefinitely.&lt;br /&gt;//&lt;br /&gt;// Returns:&lt;br /&gt;// The array index of the object that satisfied the wait.&lt;br /&gt;[PrePrepareMethod]&lt;br /&gt;[CLSCompliant(false)]&lt;br /&gt;public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);&lt;br /&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// Helper function that waits for any or all the elements in the specified array&lt;br /&gt;// to receive a signal.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// waitHandles:&lt;br /&gt;// An array of type System.IntPtr that contains the native operating system&lt;br /&gt;// handles.&lt;br /&gt;//&lt;br /&gt;// waitAll:&lt;br /&gt;// true to wait for all handles; false to wait for any handle.&lt;br /&gt;//&lt;br /&gt;// millisecondsTimeout:&lt;br /&gt;// The number of milliseconds to wait, or System.Threading.Timeout.Infinite&lt;br /&gt;// (-1) to wait indefinitely.&lt;br /&gt;//&lt;br /&gt;// Returns:&lt;br /&gt;// The array index of the object that satisfied the wait.&lt;br /&gt;[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]&lt;br /&gt;[PrePrepareMethod]&lt;br /&gt;[CLSCompliant(false)]&lt;br /&gt;protected static int WaitHelper(IntPtr[] waitHandles,&lt;br /&gt;bool waitAll, int millisecondsTimeout);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice the comment for the &lt;code&gt;Post&lt;/code&gt; method:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;//&lt;br /&gt;// Summary:&lt;br /&gt;// When overridden in a derived class, dispatches an asynchronous message to&lt;br /&gt;// a synchronization context.&lt;br /&gt;//&lt;br /&gt;// Parameters:&lt;br /&gt;// d:&lt;br /&gt;// The System.Threading.SendOrPostCallback delegate to call.&lt;br /&gt;//&lt;br /&gt;// state:&lt;br /&gt;// The object passed to the delegate.&lt;br /&gt;public virtual void Post(SendOrPostCallback d, object state);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The key word here is &lt;strong&gt;asynchronous&lt;/strong&gt;. This means that &lt;code&gt;Post&lt;/code&gt; will not wait for the execution of the delegate to complete. &lt;code&gt;Post&lt;/code&gt; will "Fire and Forget" about the execution code within the delegate. It also means that you can not catch exceptions as we did with the &lt;code&gt;Send&lt;/code&gt; method. Suppose an exception is thrown, it will be the UI thread that will get it; unhanding the exception will terminate the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;However, &lt;code&gt;Post&lt;/code&gt; or &lt;code&gt;Send&lt;/code&gt;, the execution of the delegate always runs on the correct thread. Just replace the code with &lt;code&gt;Post&lt;/code&gt; instead of &lt;code&gt;Send&lt;/code&gt;, and you will still get the right thread ID when executing on the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;So now, I can use SynchronizationContext to sync any thread I want, right? Nope!&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;At this point, you might try to use &lt;code&gt;SynchronizationContext&lt;/code&gt; with any thread. However, you will soon find that your thread does not have a &lt;code&gt;SynchronizationContext&lt;/code&gt; when using &lt;code&gt;SynchronizationContext.Current&lt;/code&gt;, and it always returns &lt;code lang="cs"&gt;null&lt;/code&gt;. No big deal you say, and you simply create a &lt;code&gt;SynchronizationContext&lt;/code&gt; if there isn't one. Simple. But, it does not really work.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let's look at a program similar to the one we used for the UI thread:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;class Program&lt;br /&gt;{&lt;br /&gt;private static SynchronizationContext mT1 = null;&lt;br /&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;// log the thread id&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Console.WriteLine("Main thread is " + id);&lt;br /&gt;// create a sync context for this thread&lt;br /&gt;var context = new SynchronizationContext();&lt;br /&gt;// set this context for this thread.&lt;br /&gt;SynchronizationContext.SetSynchronizationContext(context);&lt;br /&gt;// create a thread, and pass it the main sync context.&lt;br /&gt;Thread t1 = new Thread(new ParameterizedThreadStart(Run1));&lt;br /&gt;t1.Start(SynchronizationContext.Current);&lt;br /&gt;Console.ReadLine();&lt;br /&gt;}&lt;br /&gt;static private void Run1(object state)&lt;br /&gt;{&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Console.WriteLine("Run1 Thread ID: " + id);&lt;br /&gt;// grab the sync context that main has set&lt;br /&gt;var context = state as SynchronizationContext;&lt;br /&gt;// call the sync context of main, expecting&lt;br /&gt;// the following code to run on the main thread&lt;br /&gt;// but it will not.&lt;br /&gt;context.Send(DoWork, null);&lt;br /&gt;while (true)&lt;br /&gt;Thread.Sleep(10000000);&lt;br /&gt;}&lt;br /&gt;static void DoWork(object state)&lt;br /&gt;{&lt;br /&gt;int id = Thread.CurrentThread.ManagedThreadId;&lt;br /&gt;Console.WriteLine("DoWork Thread ID:" + id);&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This simple console application is something you should not do at home. This program does not work, and it is done simply to prove a point. Notice I am setting a Sync Context on the main console thread. I am simply creating a new instance of the object. Then, I am setting it to my current thread. This is similar to what the UI thread does when a form is created (not really, but I will explain later). Then, I create a thread &lt;code&gt;Run1&lt;/code&gt;, and pass it the context of the main thread. When I try to call &lt;code&gt;Send&lt;/code&gt;, based on my trace, I notice &lt;code&gt;Send&lt;/code&gt; was called on the &lt;code&gt;Run1&lt;/code&gt; thread and not on the main thread as we may expect. Here is the output:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="text"&gt;Main thread is 10&lt;br /&gt;Run1 Thread ID: 11&lt;br /&gt;DoWork Thread ID:11&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice that &lt;code&gt;DoWork&lt;/code&gt; is executed on thread 11, the same thread as &lt;code&gt;Run1&lt;/code&gt;. Not much of a &lt;code&gt;SynchronizationContext&lt;/code&gt; into the main thread. Why? What's going on? Well... This is the part when you realize that nothing is for free in life. Threads can't just switch contexts between them, they must have an infrastructure built-in into them in order to do so. The UI thread, for example, uses a message pump, and within its &lt;code&gt;SynchronizationContext&lt;/code&gt;, it leverages the message pump to sync into the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So, the UI thread has it own &lt;code&gt;SynchronizationContext&lt;/code&gt; class, but it is a class that derives from &lt;code&gt;SynchronizationContext&lt;/code&gt;, and it is called &lt;code&gt;System.Windows.Forms.WindowsFormsSynchronizationContext&lt;/code&gt;. Now, this class has a very different implementation from the simple plain vanilla &lt;code&gt;SynchronizationContext&lt;/code&gt;. The UI version overrides the &lt;code&gt;Post&lt;/code&gt; and &lt;code&gt;Send&lt;/code&gt; methods, and provides a "message pump" version of these methods (I tried to get the source code of this class, but I didn't find it). So, what does the plain vanilla &lt;code&gt;SynchronizationContext&lt;/code&gt; do?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Somehow, I was able to get the source code of &lt;code&gt;SynchronizationContext&lt;/code&gt;, and here it is: &lt;a href="http://www.koders.com/csharp/fid874F22E35DC2F0B76C07FACB4F4CFDE95C28D488.aspx"&gt;found it here&lt;/a&gt;.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;(I have removed the attributes, and did some minor formatting just to have the code fit in the page.)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;namespace System.Threading&lt;br /&gt;{&lt;br /&gt;using Microsoft.Win32.SafeHandles;&lt;br /&gt;using System.Security.Permissions;&lt;br /&gt;using System.Runtime.InteropServices;&lt;br /&gt;using System.Runtime.CompilerServices;&lt;br /&gt;using System.Runtime.ConstrainedExecution;&lt;br /&gt;using System.Reflection;&lt;br /&gt;&lt;br /&gt;internal struct SynchronizationContextSwitcher : IDisposable&lt;br /&gt;{&lt;br /&gt;internal SynchronizationContext savedSC;&lt;br /&gt;internal SynchronizationContext currSC;&lt;br /&gt;internal ExecutionContext _ec;&lt;br /&gt;public override bool Equals(Object obj)&lt;br /&gt;{&lt;br /&gt;if (obj == null !(obj is SynchronizationContextSwitcher))&lt;br /&gt;return false;&lt;br /&gt;SynchronizationContextSwitcher sw = (SynchronizationContextSwitcher)obj;&lt;br /&gt;return (this.savedSC == sw.savedSC &amp;amp;&amp;amp;&lt;br /&gt;this.currSC == sw.currSC &amp;amp;&amp;amp; this._ec == sw._ec);&lt;br /&gt;}&lt;br /&gt;public override int GetHashCode()&lt;br /&gt;{&lt;br /&gt;return ToString().GetHashCode();&lt;br /&gt;}&lt;br /&gt;public static bool operator ==(SynchronizationContextSwitcher c1,&lt;br /&gt;SynchronizationContextSwitcher c2)&lt;br /&gt;{&lt;br /&gt;return c1.Equals(c2);&lt;br /&gt;}&lt;br /&gt;public static bool operator !=(SynchronizationContextSwitcher c1,&lt;br /&gt;SynchronizationContextSwitcher c2)&lt;br /&gt;{&lt;br /&gt;return !c1.Equals(c2);&lt;br /&gt;}&lt;br /&gt;void IDisposable.Dispose()&lt;br /&gt;{&lt;br /&gt;Undo();&lt;br /&gt;}&lt;br /&gt;internal bool UndoNoThrow()&lt;br /&gt;{&lt;br /&gt;if (_ec == null)&lt;br /&gt;{&lt;br /&gt;return true;&lt;br /&gt;}&lt;br /&gt;try&lt;br /&gt;{&lt;br /&gt;Undo();&lt;br /&gt;}&lt;br /&gt;catch&lt;br /&gt;{&lt;br /&gt;return false;&lt;br /&gt;}&lt;br /&gt;return true;&lt;br /&gt;}&lt;br /&gt;public void Undo()&lt;br /&gt;{&lt;br /&gt;if (_ec == null)&lt;br /&gt;{&lt;br /&gt;return;&lt;br /&gt;}&lt;br /&gt;ExecutionContext executionContext =&lt;br /&gt;Thread.CurrentThread.GetExecutionContextNoCreate();&lt;br /&gt;if (_ec != executionContext)&lt;br /&gt;{&lt;br /&gt;throw new InvalidOperationException(Environment.GetResourceString(&lt;br /&gt;"InvalidOperation_SwitcherCtxMismatch"));&lt;br /&gt;}&lt;br /&gt;if (currSC != _ec.SynchronizationContext)&lt;br /&gt;{&lt;br /&gt;throw new InvalidOperationException(Environment.GetResourceString(&lt;br /&gt;"InvalidOperation_SwitcherCtxMismatch"));&lt;br /&gt;}&lt;br /&gt;BCLDebug.Assert(executionContext != null, " ExecutionContext can't be null");&lt;br /&gt;// restore the Saved Sync context as current&lt;br /&gt;executionContext.SynchronizationContext = savedSC;&lt;br /&gt;// can't reuse this anymore&lt;br /&gt;_ec = null;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public delegate void SendOrPostCallback(Object state);&lt;br /&gt;[Flags]&lt;br /&gt;enum SynchronizationContextProperties&lt;br /&gt;{&lt;br /&gt;None = 0,&lt;br /&gt;RequireWaitNotification = 0x1&lt;br /&gt;};&lt;br /&gt;public class SynchronizationContext&lt;br /&gt;{&lt;br /&gt;SynchronizationContextProperties _props = SynchronizationContextProperties.None;&lt;br /&gt;public SynchronizationContext()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// protected so that only the derived sync&lt;br /&gt;// context class can enable these flags&lt;br /&gt;protected void SetWaitNotificationRequired()&lt;br /&gt;{&lt;br /&gt;// Prepare the method so that it can be called&lt;br /&gt;// in a reliable fashion when a wait is needed.&lt;br /&gt;// This will obviously only make the Wait reliable&lt;br /&gt;// if the Wait method is itself reliable. The only thing&lt;br /&gt;// preparing the method here does is to ensure there&lt;br /&gt;// is no failure point before the method execution begins.&lt;br /&gt;RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));&lt;br /&gt;_props = SynchronizationContextProperties.RequireWaitNotification;&lt;br /&gt;}&lt;br /&gt;public bool IsWaitNotificationRequired()&lt;br /&gt;{&lt;br /&gt;return ((_props &amp;amp;&lt;br /&gt;SynchronizationContextProperties.RequireWaitNotification) != 0);&lt;br /&gt;}&lt;br /&gt;public virtual void Send(SendOrPostCallback d, Object state)&lt;br /&gt;{&lt;br /&gt;d(state);&lt;br /&gt;}&lt;br /&gt;public virtual void Post(SendOrPostCallback d, Object state)&lt;br /&gt;{&lt;br /&gt;ThreadPool.QueueUserWorkItem(new WaitCallback(d), state);&lt;br /&gt;}&lt;br /&gt;public virtual void OperationStarted()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;public virtual void OperationCompleted()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;// Method called when the CLR does a wait operation&lt;br /&gt;public virtual int Wait(IntPtr[] waitHandles,&lt;br /&gt;bool waitAll, int millisecondsTimeout)&lt;br /&gt;{&lt;br /&gt;return WaitHelper(waitHandles, waitAll, millisecondsTimeout);&lt;br /&gt;}&lt;br /&gt;// Static helper to which the above method&lt;br /&gt;// can delegate to in order to get the default&lt;br /&gt;// COM behavior.&lt;br /&gt;protected static extern int WaitHelper(IntPtr[] waitHandles,&lt;br /&gt;bool waitAll, int millisecondsTimeout);&lt;br /&gt;// set SynchronizationContext on the current thread&lt;br /&gt;public static void SetSynchronizationContext(SynchronizationContext syncContext)&lt;br /&gt;{&lt;br /&gt;SetSynchronizationContext(syncContext,&lt;br /&gt;Thread.CurrentThread.ExecutionContext.SynchronizationContext);&lt;br /&gt;}&lt;br /&gt;internal static SynchronizationContextSwitcher&lt;br /&gt;SetSynchronizationContext(SynchronizationContext syncContext,&lt;br /&gt;SynchronizationContext prevSyncContext)&lt;br /&gt;{&lt;br /&gt;// get current execution context&lt;br /&gt;ExecutionContext ec = Thread.CurrentThread.ExecutionContext;&lt;br /&gt;// create a swticher&lt;br /&gt;SynchronizationContextSwitcher scsw = new SynchronizationContextSwitcher();&lt;br /&gt;RuntimeHelpers.PrepareConstrainedRegions();&lt;br /&gt;try&lt;br /&gt;{&lt;br /&gt;// attach the switcher to the exec context&lt;br /&gt;scsw._ec = ec;&lt;br /&gt;// save the current sync context using the passed in value&lt;br /&gt;scsw.savedSC = prevSyncContext;&lt;br /&gt;// save the new sync context also&lt;br /&gt;scsw.currSC = syncContext;&lt;br /&gt;// update the current sync context to the new context&lt;br /&gt;ec.SynchronizationContext = syncContext;&lt;br /&gt;}&lt;br /&gt;catch&lt;br /&gt;{&lt;br /&gt;// Any exception means we just restore the old SyncCtx&lt;br /&gt;scsw.UndoNoThrow(); //No exception will be thrown in this Undo()&lt;br /&gt;throw;&lt;br /&gt;}&lt;br /&gt;// return switcher&lt;br /&gt;return scsw;&lt;br /&gt;}&lt;br /&gt;// Get the current SynchronizationContext on the current thread&lt;br /&gt;public static SynchronizationContext Current&lt;br /&gt;{&lt;br /&gt;get&lt;br /&gt;{&lt;br /&gt;ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();&lt;br /&gt;if (ec != null)&lt;br /&gt;return ec.SynchronizationContext;&lt;br /&gt;return null;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;// helper to Clone this SynchronizationContext,&lt;br /&gt;public virtual SynchronizationContext CreateCopy()&lt;br /&gt;{&lt;br /&gt;// the CLR dummy has an empty clone function - no member data&lt;br /&gt;return new SynchronizationContext();&lt;br /&gt;}&lt;br /&gt;private static int InvokeWaitMethodHelper(SynchronizationContext syncContext,&lt;br /&gt;IntPtr[] waitHandles,&lt;br /&gt;bool waitAll,&lt;br /&gt;int millisecondsTimeout)&lt;br /&gt;{&lt;br /&gt;return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Look at the implementation of &lt;code&gt;Send&lt;/code&gt; and &lt;code&gt;Post&lt;/code&gt;...&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public virtual void Send(SendOrPostCallback d, Object state)&lt;br /&gt;{&lt;br /&gt;d(state);&lt;br /&gt;}&lt;br /&gt;public virtual void Post(SendOrPostCallback d, Object state)&lt;br /&gt;{&lt;br /&gt;ThreadPool.QueueUserWorkItem(new WaitCallback(d), state);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;code&gt;Send&lt;/code&gt; simply calls the delegate on the calling thread (no thread switching of any kind), and &lt;code&gt;Post&lt;/code&gt; does the same thing, but simply uses the &lt;code&gt;ThreadPool&lt;/code&gt; to do it in an async fashion. In my opinion, this class should be &lt;code lang="cs"&gt;abstract&lt;/code&gt;. The default implementation of this class is confusing and useless. It is one of two reasons I decided to write this article.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I hope you know more about this class now, and you understand how to use it. Within .NET, I found two classes that provide a custom synchronization. One for the WinForms thread context and one for WPF thread context. I am sure there are more, but these are the ones I found so far. The default implementation of the class, as I showed you, does nothing to switch code from one thread to another. This is simply because threads, by default, do not have this type of a mechanism. UI threads, on the other hand, have a message pump and an OS mechanism via Windows APIs such as &lt;code&gt;SendMessage&lt;/code&gt; and &lt;code&gt;PostMessage&lt;/code&gt; to communicate with this message pump. I am sure &lt;code&gt;System.Windows.Forms.WindowsFormsSynchronizationContext&lt;/code&gt; is leveraging these windows API to perform marshalling into the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;However, this should not be the end of the road for this class. You can make your own &lt;code&gt;SynchronizationContext&lt;/code&gt;, it is really simple. In fact, I had to write one. At my work, we needed to have all COM based calls executed on an STA thread. However, our application is using the thread pool and WCF, and it was not simple to just marshal code into an STA thread. Therefore, I decided to code my own version of &lt;code&gt;SynchronizationContext&lt;/code&gt; called &lt;code&gt;StaSynchronizationContext&lt;/code&gt;. I will show how I did it in part II of this article.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Happy .NETting.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-3801031245129875956?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/3801031245129875956/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=3801031245129875956' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3801031245129875956'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3801031245129875956'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/12/understanding-syncrhronizationcontext.html' title='Understanding SyncrhronizationContext'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-8094288162255054854</id><published>2008-06-07T09:19:00.000-07:00</published><updated>2008-06-07T10:15:01.218-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='BeginInvoke'/><category scheme='http://www.blogger.com/atom/ns#' term='.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='Thread'/><category scheme='http://www.blogger.com/atom/ns#' term='Nunit'/><category scheme='http://www.blogger.com/atom/ns#' term='EndInvoke'/><title type='text'>Testing Concurrency with Nunit</title><content type='html'>&lt;a href="http://4.bp.blogspot.com/_cyvneGa_yo8/SEq99jit4VI/AAAAAAAADhc/MAFfch2v7GU/s1600-h/logo.gif"&gt;&lt;img id="BLOGGER_PHOTO_ID_5209184784217923922" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; CURSOR: hand" alt="" src="http://4.bp.blogspot.com/_cyvneGa_yo8/SEq99jit4VI/AAAAAAAADhc/MAFfch2v7GU/s200/logo.gif" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.blogger.com/www.nunit.org"&gt;&lt;/a&gt;&lt;br /&gt;Nunit is really nice for unit testing. One thing I wanted to do in my unit test is simulate multiple users using the system. Normally it would be nice to have a set of tests for single user scenario. Once those tests pass, it is nice to be able to run them in a "multi-user" environment. I didn't really want to re-code my tests to simulate a multi-user environment, and I didn't really want to create complex threading system to do it.&lt;br /&gt;&lt;br /&gt;So to solve the problem I used the .NET built-in thread pool, and I leverage the existing tests I have. Here is an example&lt;br /&gt;&lt;br /&gt;Suppose we have 2 simple unit tests, one to test a customer request, and the other to test updating a customer record. The implementation is not needed for this sample.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;      [TestFixture]&lt;br /&gt;&lt;br /&gt;      public class TestCustmoerUserCase&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         [Test]&lt;br /&gt;&lt;br /&gt;         public void TestProcessCustmerRequest()&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            // processing to handle a custmer request&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         [Test]&lt;br /&gt;&lt;br /&gt;         public void TestUpdateCustomer()&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            // processing to update a custmer&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;Suppose I would like to test these two scenarios in a multi-user environment. Here is one possible solution:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;      [TestFixture]&lt;br /&gt;&lt;br /&gt;      public class TestCustmerUserCaseAsync&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         private delegate void AsyncDelegate();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         [Test]&lt;br /&gt;&lt;br /&gt;         public void TestAsync()&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            TestCustmoerUserCase custTest = new TestCustmoerUserCase();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            // you can also run initalization code here, before starting the threads...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            AsyncDelegate asyncOperation = delegate&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;               custTest.TestProcessCustmerRequest();&lt;br /&gt;&lt;br /&gt;               custTest.TestUpdateCustomer();&lt;br /&gt;&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Running thread 1");&lt;br /&gt;&lt;br /&gt;            IAsyncResult r1 = asyncOperation.BeginInvoke(null, null);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Running thread 2");&lt;br /&gt;&lt;br /&gt;            IAsyncResult r2 = asyncOperation.BeginInvoke(null, null);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Running thread 3");&lt;br /&gt;&lt;br /&gt;            IAsyncResult r3 = asyncOperation.BeginInvoke(null, null);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Waiting for threads to finish");&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            asyncOperation.EndInvoke(r1);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Finished thread 1");&lt;br /&gt;&lt;br /&gt;            asyncOperation.EndInvoke(r2);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Finished thread 2");&lt;br /&gt;&lt;br /&gt;            asyncOperation.EndInvoke(r3);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Finished thread 3");&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;br /&gt;Lets make a few notes about the example above &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;I have created a delegate using .NET C# 2.0 anonymous methods. This allows me to place a method within a method and give it a delegate name. In this case my delegate is called&lt;br /&gt;asyncOperation.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Within the body of asyncOperation are the unit tests calls (which we normally call from a single thread). Note that declaring the delegate does not execute it.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Right after declaring my delegate I ask .NET to invoke it 3 times on the thread pool. I do this with the BeginInvoke method, which each .NET delegate support. &lt;/li&gt;&lt;br /&gt;&lt;li&gt;I pass null for callback, and null for state. That's because in this case I don't need them&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Each time a BeginInvoke is called, I get a "token" for the threaded execution called IAsyncResult. Its important to keep all 3 references I get from BeginInvoke. (in this example they are saved as r1, r2 and r3&lt;/li&gt;&lt;br /&gt;&lt;li&gt;After launching the 3 threads. I need to wait for them to finish. Calling EndInvoke waits for the execution to finish, but which one? this is where the IAsyncResult plays an important role.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;EndInvoke(r1) will wait for the first thread to finish, EndInvoke(r2) waits for the second thread ... as so on.&lt;/li&gt;&lt;li&gt;I could of used a loop and an array to store the IAsyncResults, but that would of made the example more complex. For production use, you should use a loop and array for running the threads.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So there you have it. You ran a set of unit tests that you already have without too much work. But, remember multi-threading requires a few things:&lt;/p&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Your unit tests need to be thread safe! its best that they don't share memory, or the small amount of memory they do share is protected between threads. &lt;/li&gt;&lt;li&gt;&lt;div align="left"&gt;For more on Nunit go see &lt;a href="http://www.nunit.org/"&gt;http://www.nunit.org/&lt;/a&gt; &lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p align="left"&gt;Happy .Netting everyone.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-8094288162255054854?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/8094288162255054854/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=8094288162255054854' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8094288162255054854'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8094288162255054854'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/06/testing-concurrency-with-nunit.html' title='Testing Concurrency with Nunit'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_cyvneGa_yo8/SEq99jit4VI/AAAAAAAADhc/MAFfch2v7GU/s72-c/logo.gif' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-4095168322552923963</id><published>2008-05-17T06:55:00.000-07:00</published><updated>2008-05-19T06:57:47.217-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><category scheme='http://www.blogger.com/atom/ns#' term='Friend'/><title type='text'>Using Friends with C#, or should I say Bully</title><content type='html'>&lt;a href="http://1.bp.blogspot.com/_cyvneGa_yo8/SDGHS5vKv2I/AAAAAAAADgw/J1VoMiJD60E/s1600-h/bully.gif"&gt;&lt;img id="BLOGGER_PHOTO_ID_5202087803395686242" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; CURSOR: hand" alt="" src="http://1.bp.blogspot.com/_cyvneGa_yo8/SDGHS5vKv2I/AAAAAAAADgw/J1VoMiJD60E/s320/bully.gif" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="font-family:arial;"&gt;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="font-family:arial;"&gt;One feature that is missing in C# is the use of Friends, something you can do with C++. There are valid reasons why C# doesn't really support friends, mostly because it breaks OO design. However it would be nice to have something similar. .NET offers the use of &lt;code&gt;internal&lt;/code&gt; keyword, which does provide some features similar to friend but it is not the same.&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:Arial;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:Arial;"&gt;I wanted to do something simple, having a class that can set the private data of another class. Without the use of Reflection, I noticed this was not possible, so I tried to do the next best thing. Having a class able to set the value of a protected item within another class, but without directly inherting from it. To solve the issue, I decided to use a combination of inheritance and nested private classes. Below &lt;/span&gt;&lt;span style="font-family:Arial;"&gt;is an example:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;    public class Bob&lt;br /&gt;&lt;br /&gt;    {  &lt;br /&gt;&lt;br /&gt;        private string mMyBestFriend;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public string Friend&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            get { return mMyBestFriend; }&lt;br /&gt;&lt;br /&gt;            protected set { mMyBestFriend = value; }&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    public class Mike&lt;br /&gt;&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        public Mike()&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;      &lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public void MakeMeAFriendOfBob(Bob bob)&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            // use the inner class to access the name field.&lt;br /&gt;&lt;br /&gt;            new SetFriend().SetFriendName(bob, "Mike");&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private class SetFriend : Bob&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            public SetFriend()&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;          &lt;br /&gt;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            public void SetFriendName(Bob bob, string name)&lt;br /&gt;&lt;br /&gt;            {          &lt;br /&gt;&lt;br /&gt;                bob.Friend = name;&lt;br /&gt;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Notice in the example above, that the class Mike is able to set a protected field within the class Bob. Mike is now a friend of Bob in a way. I used an inner private class to handle the inheritance so the class Mike does not need to inherit from Bob directly. There is a reason I said this is like Mike is a Bully, because Bob never really specified who are its friends, as you can do in C++, using simple inheritance I forced Mike to bully its way into Bob. &lt;/p&gt;&lt;br /&gt;&lt;div&gt;The main program can do somthing like this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;            Mike me = new Mike();&lt;br /&gt;&lt;br /&gt;            Bob bob = new Bob();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            me.MakeMeAFriendOfBob(bob);&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;Below is another example, allowing one class to set the value of a static field within another class. The static field however is not public, so only certain classes can set it. Same concept as above.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;    public class Registry&lt;br /&gt;&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        private static string mValue;&lt;br /&gt;&lt;br /&gt;   &lt;br /&gt;&lt;br /&gt;        // only certain classes can set the value&lt;br /&gt;&lt;br /&gt;        protected string RegisterValue&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            set&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;                mValue = value;&lt;br /&gt;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        // other classes can read the vlaue&lt;br /&gt;&lt;br /&gt;        public static string RegisteredValue&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            get { return mValue; }&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    // notice that FriendOfRegistry does not inhert directly from Registry&lt;br /&gt;&lt;br /&gt;    public class FriendOfRegistry&lt;br /&gt;&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        public FriendOfRegistry()&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            // at this point I would like to register my value&lt;br /&gt;&lt;br /&gt;            new RegisterValueSetter("SpecialCode");&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private class RegisterValueSetter : Registry&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            public RegisterValueSetter(string value)&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;                base.RegisterValue = value;&lt;br /&gt;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        }  &lt;br /&gt;&lt;br /&gt;    }&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;h2&gt;A few notes&lt;/h2&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;This is not a perfect solution, we can always set values to protected items, we just need to use inheritance, so we are not really forcing who can be friends with who, we are just making it a little harder, so the general population can see someone's privates :), sorry I mean protected data.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Using reflection you can always set a private field, but that just evil.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;I used this concept when I wanted to register a value within a class, and make sure only a certain class can do it. the idea is that if someone notices a field to be protected, they know they should not really mess with it, unless they have a good reason.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Overall, this is not really how to make "Friend work", and that's why I consider this method more like "Bully".&lt;br /&gt;&lt;br /&gt;If you can think of other ideas to solve the Friend feature within C#, I would like to hear from you.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Happy .Netting.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-4095168322552923963?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/4095168322552923963/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=4095168322552923963' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4095168322552923963'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4095168322552923963'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/05/using-friends-with-c-or-should-i-say.html' title='Using Friends with C#, or should I say Bully'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_cyvneGa_yo8/SDGHS5vKv2I/AAAAAAAADgw/J1VoMiJD60E/s72-c/bully.gif' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1437825407892283788</id><published>2008-03-30T17:16:00.000-07:00</published><updated>2008-03-30T17:17:11.136-07:00</updated><title type='text'>MVP pattern with Windows Workflow</title><content type='html'>I am currently looking into interaction of MVP pattern with Windows Workflow. Allowing WF assist the Service layer. I am planning to use state machine workflow to do this. If anyone has done this before, or has good ideas, please send me a note or a link that I can look up for reference. I will post an example of the code once I am done.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1437825407892283788?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1437825407892283788/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1437825407892283788' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1437825407892283788'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1437825407892283788'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/03/mvp-pattern-with-windows-workflow.html' title='MVP pattern with Windows Workflow'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-2091994265408132678</id><published>2008-01-24T14:57:00.000-08:00</published><updated>2008-01-24T17:20:28.134-08:00</updated><title type='text'>Spring.net with forms - Bug!</title><content type='html'>&lt;a href="http://www.springframework.net/"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;" src="http://4.bp.blogspot.com/_cyvneGa_yo8/R5k4bOk8eBI/AAAAAAAAC6M/dRHi61iKN0A/s320/spring-logo-blue.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_5159216888550291474" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I have been trying to have an aspect around a windows form and displaying it using Application.Run method. The problem is that Application.Run wants a form object, and not an interface - this forced me to use ProxyTargetType to true with my form proxy. But doing that made Spring.net crash. It appears this is a bug with their framework and currently they are working on fixing it. I wonder if there are better ways to put aspects on forms, please post them here if you worked with Spring and windows Forms.&lt;br /&gt;&lt;br /&gt;Here is a link to the bug&lt;br /&gt;&lt;a href="http://forum.springframework.net/showthread.php?t=4252"&gt;http://forum.springframework.net/showthread.php?t=4252&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.springframework.net"&gt;Click here to go to Spring.net home web site&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-2091994265408132678?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/2091994265408132678/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=2091994265408132678' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2091994265408132678'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2091994265408132678'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/01/springnet-with-forms-bug.html' title='Spring.net with forms - Bug!'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_cyvneGa_yo8/R5k4bOk8eBI/AAAAAAAAC6M/dRHi61iKN0A/s72-c/spring-logo-blue.gif' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-2136195190683422981</id><published>2008-01-10T07:14:00.001-08:00</published><updated>2008-01-10T07:21:07.492-08:00</updated><title type='text'>MVP Article on Code Project</title><content type='html'>&lt;a href="http://1.bp.blogspot.com/_cyvneGa_yo8/R4Y2u-0dXsI/AAAAAAAACxo/lQIE28gTUiI/s1600-h/codeproject225x90.gif"&gt;&lt;img style="cursor:pointer; cursor:hand;" src="http://1.bp.blogspot.com/_cyvneGa_yo8/R4Y2u-0dXsI/AAAAAAAACxo/lQIE28gTUiI/s400/codeproject225x90.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_5153867004337020610" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I have posted the MVP article on the code project. Feel free to reivew it and comment on it there as well. You can go there by clicking &lt;a href="http://www.codeproject.com/KB/cs/ModelViewPresenterWithDI.aspx"&gt;here.&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-2136195190683422981?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/2136195190683422981/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=2136195190683422981' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2136195190683422981'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2136195190683422981'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/01/mvp-article-on-code-project.html' title='MVP Article on Code Project'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_cyvneGa_yo8/R4Y2u-0dXsI/AAAAAAAACxo/lQIE28gTUiI/s72-c/codeproject225x90.gif' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-3240895828231742533</id><published>2008-01-01T07:55:00.000-08:00</published><updated>2008-05-19T09:53:58.655-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Spring.net'/><category scheme='http://www.blogger.com/atom/ns#' term='Threading'/><category scheme='http://www.blogger.com/atom/ns#' term='MVP'/><category scheme='http://www.blogger.com/atom/ns#' term='DI'/><category scheme='http://www.blogger.com/atom/ns#' term='Depndency Injection'/><category scheme='http://www.blogger.com/atom/ns#' term='UI'/><title type='text'>MVP (Model View Presenter or Supervising Controller) with DI (Spring.Net) and Threading support</title><content type='html'>&lt;a href="http://3.bp.blogspot.com/_cyvneGa_yo8/SDGwnZvKv3I/AAAAAAAADg4/AvV80aD4g58/s1600-h/mvp.gif"&gt;&lt;img id="BLOGGER_PHOTO_ID_5202133235559743346" style="CURSOR: hand" alt="" src="http://3.bp.blogspot.com/_cyvneGa_yo8/SDGwnZvKv3I/AAAAAAAADg4/AvV80aD4g58/s320/mvp.gif" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;In this article I will show how to use the Model View Presenter pattern to remove logic from the UI and move it to a controller class. Furthermore, I will show an easy way to enable threading within the application and follow the rule of "no business work should be done in the UI thread". By applying threading correctly you should never have a situation where the UI is blocked while processing some business work.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Logon Example&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;To show the MVP pattern and all its glory I decided to use the logon screen example. We are all familiar with logon: a screen shows up asking for the user name and password. When the user presses the "Logon" button, work is initiated to validate if the user is authenticated on the system. Normally, logon is quick, however in complex systems, logging-on can take significant amount of time, I am going to show how to handle long operations with MVP, using a tiny framework which is based on the thread pool. But, first thing first, lets define our screen.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Creating the View&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Views are really our UI layer. Normally these would be web pages or win forms, in this example I will use winforms. Using MVP, the view should really expose no business logic what's so ever. In fact, if you need to add an if statement you should ask yourself if it belongs in the view or the controller, unless your if statement relates with UI work, it probably belongs in the controller. The way I see views in MVP, are classes that at the core expose only properties and events - nothing else. There could be exceptions to this rule, but the goal is to make the view very simple. The view knows how to get data, and how to set data, but it doesn't know in which sequence or why. It is like a dummy puppet that provides all the ropes but without knowing the actual act.&lt;br /&gt;&lt;br /&gt;Suppose our logon screen will have a user name field, password field, a status field (indicating if there is an error) and a button for performing the actual log-on. We can define the interface for the view without too much trouble.&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public interface ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      void Notify(string notification);&lt;br /&gt;&lt;br /&gt;      string Password { get; }&lt;br /&gt;&lt;br /&gt;      string UserName { get; }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice the interface contains a property with setter and getter for each field, and an event for pressing the log-on button. I have also added the Notify method, so I can notify my view from the outside, this method is used to setup the status field indicating if the logon is successful or not. I will talk about this method later. Using the ILogonView interface we get the extra benefit of having a view implemented in different ways, it can be a web page, or it can be a winform. It can even be a regular class - just used for testing.&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public partial class LogonForm : Form, ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      public LogonForm()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         InitializeComponent();&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the User Name from the username text box&lt;br /&gt;&lt;br /&gt;      /// Trim the user name, and always return lower case&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string UserName&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get { return mTextBoxUserName.Text.Trim().ToLower(); }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the password from the password textbox&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string Password&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            return mTextBoxPassword.Text;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Update the screen with a message&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;param name="notification"&gt;Message to show on the status bar&lt;/param&gt;&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mToolStripStatusLabelStatus.Text = notification;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      private void mButtonLogon_Click(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // fire the event that the button was clicked.&lt;br /&gt;&lt;br /&gt;         if (LogonEvent != null)&lt;br /&gt;&lt;br /&gt;            LogonEvent(this, EventArgs.Empty);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;The Controller&lt;/h2&gt;&lt;br /&gt;The job of the controller (or the presenter) is to handle the events coming from the view, and use the view getters and setters properties to define the behavior of the view. Think of the view as a data source, just like a data layer, you can query the view for information and you set information to the view. The controller is the only component that knows exactly how to manipulate the view, and how to call the setters and getters in the right sequence.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public class LogonController&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      private ILogonView mView;&lt;br /&gt;&lt;br /&gt;      public LogonController(ILogonView view)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      void mView_LogonEvent(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         string userName = mView.UserName;&lt;br /&gt;&lt;br /&gt;         string password = mView.Password;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         if ((userName == "mike") &amp;amp;&amp;amp; (password == "aop"))&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mView.Notify("User Logged On");&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mView.Notify("Invlid user name or password");&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;The controller is listening to the logon event that the view fires. When a logon event handler is triggered, the controller queries the user name and user password and validats if the user name and password are correct. If there is an error message, the controller sets the status message on the view with a message. However there are a few problems... First, I don't know if you noticed, when I first showed the code of the view, it does not contain a reference to the controller. Therefore I need to modify my Form to include knowledge of the controller&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public partial class LogonForm : Form, ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      private LogonController mController;&lt;br /&gt;&lt;br /&gt;      public LogonForm()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         InitializeComponent();&lt;br /&gt;&lt;br /&gt;         mController = new LogonController(this);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   // rest of the class unchanged&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;So far we are classic MVP, if you understand everything to this point, you have just understood MVP. Anything above this point is just little things that bug me.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The controller is doing all the work, normally the logon work should not be done directly by the controller but delegated to a business layer class to handle the logon, ideally, a logon service.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;What if the logon takes 10 minutes to process, we can not keep the view frozen.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;What if we would like to send status back to the view during a business operation outside of the controller. how do we handle that?&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;To be honest with you, I still feel the view should be beyond stupid and not know anything. But, as you can see the view knows about its controller, and how to create it.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Using a service Layer&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;OK. one problem at a time. The first task would be to remove the logon processing from the controller and move it to a service layer. Let's create a LogonService class, which accepts a user name and a password, and validates if the user is valid. Now we will use our service layer from the controller to perform the logon operation. Same idea, the controller handles the logon event handler and delegates the work to the service layer. The service layer actually does the work of logging and updates the status message on the screen with the outcome of the operation.&lt;/p&gt;We can create a simple service that looks like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public class LogonService&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public bool Logon(string userName, string password)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         bool rc;&lt;br /&gt;&lt;br /&gt;         if ((userName == "mike") &amp;amp;&amp;amp; (password == "aop"))&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            rc = true;      &lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            rc = false;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;But, here again, we have some problems. What if our service is a long running service, and maybe executes many steps to log a user. This example is simple, but let's face it is never that simple in production code. We normally have to go to the database to validate a user, I would like to provide the service some way to report status back to the view. After all, our controller can do this, so should the service... An idea would be to introduce an interface to allow the service report status something like INotify&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public interface INotify&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      void Notify(string notification);&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now this should look familiar, our View has this method... (take a look)&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   public interface ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      void Notify(string notification);&lt;br /&gt;&lt;br /&gt;      string Password { get; }&lt;br /&gt;&lt;br /&gt;      string UserName { get; }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;So, lets break this into 2 interfaces...&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public interface INotify&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      void Notify(string notification);&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   public interface ILogonView : INotify&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      string Password { get; }&lt;br /&gt;&lt;br /&gt;      string UserName { get; }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice that ILogonView inherits from INotify. Now we need to pass this INotify to the service, so lets modify our service. Other then that little change there nothing new with our View. Lets look at the controller using the&lt;br /&gt;&lt;br /&gt;LogonService class.&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public class LogonController&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      private ILogonView mView;&lt;br /&gt;&lt;br /&gt;      public LogonController(ILogonView view)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      void mView_LogonEvent(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         string userName = mView.UserName;&lt;br /&gt;&lt;br /&gt;         string password = mView.Password;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         LogonService logonService = new LogonService(mView);&lt;br /&gt;&lt;br /&gt;         logonService.Logon(userName, password);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   public class LogonService&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      private INotify mNotifier;&lt;br /&gt;&lt;br /&gt;      public LogonService(INotify notifier)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mNotifier = notifier;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public bool Logon(string userName, string password)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         bool rc;&lt;br /&gt;&lt;br /&gt;         if ((userName == "mike") &amp;amp;&amp;amp; (password == "aop"))&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Logon Successful");&lt;br /&gt;&lt;br /&gt;            rc = true;      &lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Invliad User or Password");&lt;br /&gt;&lt;br /&gt;            rc = false;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         return rc;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Notice a few things:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The service is created as a local variable to the event handler, it might be better to create the service once and keep it during the lifetime of the controller, but then we have the problem of who creates the service? It could be passed to the controller on the constructor or created directly in the Controller, but then it might not be re-used by other controllers. Best approach is to pass the service to the constructor, but I am not willing to have the view create it and pass it. I will deal with this issue soon.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The service is passing the view as an INotify, there is really nothing wrong with that, but if you think about it allows the service direct access to the UI. A better way would be to have the service talk to the Controller via INotify. Then we are respecting the role of the controller... (so I am going to make this change by allowing the controller to implement INotify&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The goal was to provide the service a channel to communicate to the view, so now it is possible for a long running service to report status. But, what if we don't want to report anything, and would like to run the service without a view and without a UI, notice that you can't create the service without INotify. So here is another problem, which I will deal with later. At least we can say the logic of the logon is now outside of the controller, and our service is a little more powerful with its capabilities&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;A note about DDD (Domain Driven Design), notice my service is not very domain driven, it is normally at the service level that we should see classes such as User, and Authentication, For example &lt;code&gt;Autentication.Autenticate(User user)&lt;/code&gt;, but I am leaving the domain model out of this article, because already I have a lot of problems to solve and DDD deserve an article on its own.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Lets do a bit of re-factoring, first step, lets create the service as a member variable of the controller class. Lets also have the ability to pass the service to the constructor&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;      public LogonController(ILogonView view)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         mLogonService = new LogonService(this);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      // set the serivce by the client (but not used for now).&lt;br /&gt;&lt;br /&gt;      public LogonController(ILogonView view, LogonService logonService)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         mLogonService = logonService;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      void mView_LogonEvent(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         string userName = mView.UserName;&lt;br /&gt;&lt;br /&gt;         string password = mView.Password;&lt;br /&gt;&lt;br /&gt;         mLogonService.Logon(userName, password);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      // used to implemnt INotify&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mView.Notify(notification);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The controller implements INotify&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The service can be passed to the controller, it's more flexible. But I am not changing the view, so this constructor will not be used&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;I created the service as a member variable if it is not passed.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;OK. Lets step back a little, most of you might be happy with this implementation of MVP, and it is kind of by the book. But, I am still not happy with it. First of all, who is going to create the LogonService, it should really be set outside of the controller, or supplied to the controller (but I hate having the view create the service. Same problem with the Controller being created by the view. The view should have no knowledge of how to create a controller, it would be nice if the controller can be supplied to the view. The solution is to have a factory pattern to create the controller, service and even the view! The solution to all these problems can be addressed with Dependency Injection (DI). &lt;/p&gt;&lt;br /&gt;&lt;p&gt;The View depends on a Controller, and my Controller depends on a service. I can create a Factory that will create my view, addressing all the dependencies, and what do you know, there is a framework out there just for that - Spring.Net.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Using Spring.NET for Dependency Injection&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To tell you all the truth, I am new to Dependency Injection, however it was not complicated to learn, and it solves the issues of object creation and dependecies. I chose to resolve all dependecies using setters properites. I have also created interfaces to all the classes that require depndecy injection&lt;br /&gt;&lt;br /&gt;The controller interface: &lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public interface ILogonController : INotify&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      ILogonView LogonView { get; set; }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Setting the view to the controller, rather then passing the view as parameter into the constructure. Now the controller can have a empty default constructure.&lt;br /&gt;&lt;br /&gt;Lets see the newly modified controller &lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public class LogonController : INotify, ILogonController&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      private ILogonView mView;&lt;br /&gt;&lt;br /&gt;      private ILogonService mLogonService;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public LogonController()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public LogonController(ILogonView view)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         mLogonService = new LogonService(this);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      // set the serivce by the client (but not used for now).&lt;br /&gt;&lt;br /&gt;      public LogonController(ILogonView view, LogonService logonService)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // register the view&lt;br /&gt;&lt;br /&gt;         mView = view;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         // listen to the view logon event&lt;br /&gt;&lt;br /&gt;         mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         mLogonService = logonService;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      void mView_LogonEvent(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // make sure the view is attached&lt;br /&gt;&lt;br /&gt;         Debug.Assert(mView != null, "view not attached");&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         string userName = mView.UserName;&lt;br /&gt;&lt;br /&gt;         string password = mView.Password;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         mLogonService.Logon(userName, password);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      // used to implemnt INotify&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mView.Notify(notification);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public ILogonService LogonService&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         set&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mLogonService = value;&lt;br /&gt;&lt;br /&gt;            mLogonService.Notifier = this;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            return mLogonService;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public ILogonView LogonView&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         set&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mView = value;&lt;br /&gt;&lt;br /&gt;            mView.LogonEvent += new EventHandler(mView_LogonEvent);&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            return mView;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Now when setting the LogonView property, the view is attached to the controller. Spring.Net will handle this for us.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Because this controller can be created using an empty constructure, I added an Assert, to make sure the view is attached when handling the logon event handler&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Notice there is a setter property for the LogonService, After setting the service, the controller sets the Notify property of the service.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;In order to inject the service into the controller, I needed to first make an interface to the service. Lets take a look at the service interface and the service class:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public interface ILogonService&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      bool Logon(string userName, string password);&lt;br /&gt;&lt;br /&gt;      INotify Notifier { get; set; }&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   public class LogonService : ILogonService&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      private INotify mNotifier;&lt;br /&gt;&lt;br /&gt;      public LogonService()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // instead of having it as null&lt;br /&gt;&lt;br /&gt;         mNotifier = new EmptyNotify();&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public LogonService(INotify notifier)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mNotifier = notifier;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public bool Logon(string userName, string password)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         bool rc;&lt;br /&gt;&lt;br /&gt;         if ((userName == "mike") &amp;amp;&amp;amp; (password == "aop"))&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Logon Successful");&lt;br /&gt;&lt;br /&gt;            rc = true;      &lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Invliad User or Password");&lt;br /&gt;&lt;br /&gt;            rc = false;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         return rc;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public INotify Notifier&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         set { mNotifier = value; }&lt;br /&gt;&lt;br /&gt;         get { return mNotifier; }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The logon service interface now allows an INotify to be specified as a setter (so if I wanted, it could of been initialized using DI as well, but I am not doing it in this example&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;I provide an empty constructor, so now I don't need to have a notify object for creating or running the service. However, in case the INotify is not passed to the constructor or not set by the setter, I provide an EmptyNotify which is similar to having the mNofity set to null. However, because this empty class implements the interface, I don't need to check in my code if the INotify object is null, or if is passed.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Here a quick look at the EmptyNotify (which is like a Null)&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  public class EmptyNotify : INotify&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         return; // do nothing.&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Lets see how the view is changed&lt;br /&gt;&lt;br /&gt;The nice thing about the new version of the view is that it is now simpler, the goal was always to keep the view unaware of business work and even something simple as creating the controller is now outside of the view. Like anything in MVP, there is a property to set the controller.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;      public ILogonController LogonController&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         set&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mController = value;&lt;br /&gt;&lt;br /&gt;            mController.LogonView = this;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice that right after the controller is set, I assign the view to the controller LogonView property. Here is the full source code of the view after the modification.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   public partial class LogonForm : Form, ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      private ILogonController mController;&lt;br /&gt;&lt;br /&gt;      public LogonForm()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         InitializeComponent();&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the User Name from the username text box&lt;br /&gt;&lt;br /&gt;      /// Trim the user name, and always return lower case&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string UserName&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get { return mTextBoxUserName.Text.Trim().ToLower(); }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the password from the password textbox&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string Password&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            return mTextBoxPassword.Text;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public ILogonController LogonController&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         set&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mController = value;&lt;br /&gt;&lt;br /&gt;            mController.LogonView = this;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Update the screen with a message&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;param name="notification"&gt;Message to show on the status bar&lt;/param&gt;&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         mToolStripStatusLabelStatus.Text = notification;&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      private void mButtonLogon_Click(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // fire the event that the button was clicked.&lt;br /&gt;&lt;br /&gt;         if (LogonEvent != null)&lt;br /&gt;&lt;br /&gt;            LogonEvent(this, EventArgs.Empty);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Setting Spring.Net&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;So far I have tried to avoid talking about Spring.Net, but at this point we are ready to deal with&lt;br /&gt;Dependency Injection. First step is to get Spring.Net and install it. Don't worry it is safe, I have done it many times it will not break anything on your computer. You can download Spring.Net from http://www.springframework.net/&lt;br /&gt;&lt;br /&gt;This example is using version 1.1 of Spring.Net&lt;br /&gt;&lt;br /&gt;Next step is adding a file reference to Spring.Core.dll into the .NET project.&lt;br /&gt;&lt;br /&gt;Now, that we have Spring.net, all that is left is to specify the dependencies for creating the objects (view, controller and service). To do this I have used the app.config to specify the dependencies in XML. The XML is simple to understand here is a copy of my App.Config for the Logon MVP example:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;p&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;configSections&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;sectionGroup name="spring"&amp;gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/&amp;gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;/sectionGroup&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;/configSections&amp;gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;   &amp;lt;spring&amp;gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;      &amp;lt;context&amp;gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;resource uri="config://spring/objects"/&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;/context&amp;gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;      &amp;lt;objects xmlns="&lt;a href="http://www.springframework.net/"&gt;http://www.springframework.net/&lt;/a&gt;"&amp;gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;         &amp;lt;object id ="LogonService" type="MvpExample.LogonService, MvpExample"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;object id="LogonController" type="MvpExample.LogonController, MvpExample"&amp;gt;&lt;br /&gt;&lt;br /&gt;            &amp;lt;property name="LogonService" ref="LogonService"/&amp;gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;/object&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;object id="LogonView" type="MvpExample.LogonForm, MvpExample"&amp;gt;&lt;br /&gt;&lt;br /&gt;            &amp;lt;property name="LogonController" ref="LogonController"/&amp;gt;&lt;br /&gt;&lt;br /&gt;         &amp;lt;/object&amp;gt;                                       &lt;br /&gt;&lt;br /&gt;      &amp;lt;/objects&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;/spring&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The Object ID tag is just a logical name&lt;br /&gt;&lt;br /&gt;&lt;li&gt;I have setup the LogonView, to have its property LogonController set to the object definition of "LogonController"&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Similar case with the setting the LogonService logical name into the LogonController property "LogonService"&lt;br /&gt;&lt;br /&gt;All that is left, is just to create the root object, the view within my application. Notice the changes to Program.cs&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;   static class Program&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// The main entry point for the application.&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      [STAThread]&lt;br /&gt;&lt;br /&gt;      static void Main()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         Application.EnableVisualStyles();&lt;br /&gt;&lt;br /&gt;         Application.SetCompatibleTextRenderingDefault(false);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         IApplicationContext ctx = ContextRegistry.GetContext();&lt;br /&gt;&lt;br /&gt;         Form logonForm = ctx.GetObject("LogonView") as Form;&lt;br /&gt;&lt;br /&gt;         Application.Run(logonForm);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The most important part are the Spring.net application context:&lt;br /&gt;&lt;pre&gt;IApplicationContext ctx = ContextRegistry.GetContext();&lt;br /&gt;&lt;br /&gt;         Form logonForm = ctx.GetObject("LogonView") as Form;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here we are asking Spring.Net to create our View object, by specifying its Logical Name LogonView, the name must match the name in the app.config&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;p&gt;&amp;lt;object id="LogonView" type="MvpExample.LogonForm, MvpExample"&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;property name="LogonController" ref="LogonController"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/object&amp;gt;&lt;/p&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;All the other dependencies are taken care of by using Spring.Net. At this point our Logon application is initialized with the correct version of a view, controller and service. Notice that this allows us to "switch" the implementation of a dependency, just by providing a new implementation of an interface and configuration change. For example, to provide another version of the LogonService that willcontain&lt;br /&gt;additional work, we just need to tell Spring.Net which version to "inject". At this point I wanted to finish my article, but I noticed that there is one more issue with this MVP&lt;br /&gt;pattern. The case of having a long running service, and the risk of freezing the UI while processing the service. To solve this problem I have introduced a simple but yet powerful little threading framework.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The UI should never freeze&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;The main problem with UI and threads, is that the UI is not allowed to accessible from any other the thread then the thread it was created. This means that if our application starts to create threads, and performs processing in threads, it is not legal to have these threads update the UI (via an interface or not). In fact, trying to update the UI from another thread will cause a runtime exception in .NET 2.0, and unpredictable results in version 1.1&lt;br /&gt;&lt;br /&gt;So, our first goal is to make sure the UI is able to update correctly no matter from which thread it is called on. To do this, I have added a base class to my LogonForm called View. My base class contains only one method, UpdateUI, this method accepts a delegate of type MethodInvoker and makes sure this delegate is executed on the UI thread.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public class View : Form&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      protected void UpdateUI(MethodInvoker uiDelegate)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         if (InvokeRequired)&lt;br /&gt;&lt;br /&gt;            this.Invoke(uiDelegate);&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;            uiDelegate();&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;I am planning to use the same delegate for all my UI activities. This should make you wonder, how a delegate that takes no arguments and no return values is able to satisfy all UI operations.&lt;br /&gt;&lt;br /&gt;Here is a trick... I use Anonymous methods to wrap all UI operations... lets look at a simple example:&lt;br /&gt;&lt;br /&gt;Getting the user name from the UI should be done on the UI thread, so I would like to wrap the code that gets the user name from the textbox into a MethodInvoker delegate&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Before:&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;      public string UserName&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            return mTextBoxUserName.Text.Trim().ToLower();&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;After:&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;      public string UserName&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            string value = null;&lt;br /&gt;&lt;br /&gt;            MethodInvoker uiDelegate = delegate&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;               value = mTextBoxUserName.Text.Trim().ToLower();&lt;br /&gt;&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            UpdateUI(uiDelegate);&lt;br /&gt;&lt;br /&gt;            return value;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Notice: for the getters, I needed to store the return value outside of my anonymous method. This is because my delegate does not accept a return value. This is an issue I plan to resolved in a second part of the article... (using AOP to handle UI thread safely). Now, we have to surround all our View public methods with this uiDelegate. To make the job simpler I made a C# Snippet that allows you to select the code within the property, and then apply the "view thread safe"&lt;br /&gt;&lt;br /&gt;snippet. Here is the snippet, if you want to use it.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;pre&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;CodeSnippet Format="1.0.0"&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;Header&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Title&amp;gt;View Thread Safe&amp;lt;/Title&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Shortcut&amp;gt;view&amp;lt;/Shortcut&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Description&amp;gt;Code snippet for creating thread safe view code&amp;lt;/Description&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Author&amp;gt;Atrion Corporation&amp;lt;/Author&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;SnippetTypes&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;SnippetType&amp;gt;Expansion&amp;lt;/SnippetType&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;SnippetType&amp;gt;SurroundsWith&amp;lt;/SnippetType&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;/SnippetTypes&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;/Header&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;Snippet&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Declarations&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;Literal&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;ID&amp;gt;delegate&amp;lt;/ID&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;ToolTip&amp;gt;Delegate to call&amp;lt;/ToolTip&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;Default&amp;gt;uiDelegate&amp;lt;/Default&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;/Literal&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;Literal&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;ID&amp;gt;method&amp;lt;/ID&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;ToolTip&amp;gt;Function to handle the threading&amp;lt;/ToolTip&amp;gt;&lt;br /&gt;&lt;br /&gt;     &amp;lt;Default&amp;gt;UpdateUI&amp;lt;/Default&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;/Literal&amp;gt;&lt;br /&gt;&lt;br /&gt;     &lt;br /&gt;&lt;br /&gt;   &amp;lt;/Declarations&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;Code Language="csharp"&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;&lt;br /&gt;        MethodInvoker $delegate$ = delegate&lt;br /&gt;&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;         $selected$ $end$&lt;br /&gt;&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        $method$($delegate$);&lt;br /&gt;&lt;br /&gt; $end$]]&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;/Code&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;/Snippet&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;/CodeSnippet&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/CodeSnippets&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Lets look at our new View method:&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public partial class LogonForm : View, ILogonView&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public event EventHandler LogonEvent;&lt;br /&gt;&lt;br /&gt;      private ILogonController mController;&lt;br /&gt;&lt;br /&gt;      public LogonForm()&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         InitializeComponent();&lt;br /&gt;&lt;br /&gt;         //mController = new LogonController(this);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the User Name from the username text box&lt;br /&gt;&lt;br /&gt;      /// Trim the user name, and always return lower case&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string UserName&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            string value = null;&lt;br /&gt;&lt;br /&gt;            MethodInvoker uiDelegate = delegate&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;               value = mTextBoxUserName.Text.Trim().ToLower();&lt;br /&gt;&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            UpdateUI(uiDelegate);&lt;br /&gt;&lt;br /&gt;            return value;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Get the password from the password textbox&lt;br /&gt;&lt;br /&gt;      /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;      public string Password&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         get&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            string value = null;&lt;br /&gt;&lt;br /&gt;            MethodInvoker uiDelegate = delegate&lt;br /&gt;&lt;br /&gt;            {&lt;br /&gt;&lt;br /&gt;                value = mTextBoxPassword.Text;&lt;br /&gt;&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            UpdateUI(uiDelegate);&lt;br /&gt;&lt;br /&gt;            return value;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      public ILogonController LogonController&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;          set&lt;br /&gt;&lt;br /&gt;          {&lt;br /&gt;&lt;br /&gt;            mController = value;&lt;br /&gt;&lt;br /&gt;            mController.LogonView = this;&lt;br /&gt;&lt;br /&gt;          }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      /// &lt;summary&gt;&lt;br /&gt;&lt;br /&gt;      /// Update the screen with a message&lt;br /&gt;&lt;br /&gt;     /// &lt;/summary&gt;&lt;br /&gt;&lt;br /&gt;     /// &lt;param name="notification"&gt;Message to show on the status bar&lt;/param&gt;&lt;br /&gt;&lt;br /&gt;      public void Notify(string notification)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         MethodInvoker uiDelegate = delegate&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mToolStripStatusLabelStatus.Text = notification;&lt;br /&gt;&lt;br /&gt;         };&lt;br /&gt;&lt;br /&gt;         UpdateUI(uiDelegate);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      private void mButtonLogon_Click(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // fire the event that the button was clicked.&lt;br /&gt;&lt;br /&gt;         if (LogonEvent != null)&lt;br /&gt;&lt;br /&gt;            LogonEvent(this, EventArgs.Empty);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Now our view is able to update itself, no matter from which thread it is being called from. Next step is to actually use threads within the controller. Suppose the logon takes 5 seconds to logon. To enable threading at the controller level I can use the same approach I used for the view. Using delegates... Notice the new base controller class.&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;   public class AsyncController&lt;br /&gt;&lt;br /&gt;   {&lt;br /&gt;&lt;br /&gt;      public delegate void AsyncDelegate();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      // must call end invoke to clean up resources by the .net runtime.&lt;br /&gt;&lt;br /&gt;      // if there is an exception, call the OnExcption which may be overridden by&lt;br /&gt;&lt;br /&gt;      // children.&lt;br /&gt;&lt;br /&gt;      protected void EndAsync(IAsyncResult ar)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // clean up only.&lt;br /&gt;&lt;br /&gt;         AsyncDelegate del = (AsyncDelegate)ar.AsyncState;&lt;br /&gt;&lt;br /&gt;         try&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            del.EndInvoke(ar);&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         catch (Exception ex)&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            OnException(ex);&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      protected void BeginInvoke(AsyncDelegate del)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // thread the delegate, as a fire and forget.&lt;br /&gt;&lt;br /&gt;         del.BeginInvoke(EndAsync, del);&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;      protected virtual void OnException(Exception ex)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;       // override by childern&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Notes:&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;By calling BeginInvoke on a delegate I am using the thread-pool&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;I don't really care for output values or return code and this is mostly due to the MVP pattern, when I implement my controller function I can know when to set values to the view.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Notice that I still make sure EndInvoke is called; this is for 2 reasons, first to make sure I get exceptions and second making sure there is no resource leak. Calling BeginInvoke without EndInvoke may cause resources to leak.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;If there is an exception, I let the child controller to take care of it. &lt;/li&gt;&lt;br /&gt;&lt;p&gt;I modified the logon service to simulate a long running operation, by Sleeping for 5 seconds&lt;/p&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;      public bool Logon(string userName, string password)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // simulate a long operation, wait 5 seconds.&lt;br /&gt;&lt;br /&gt;         System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         bool rc;&lt;br /&gt;&lt;br /&gt;         if ((userName == "mike") &amp;amp;&amp;amp; (password == "aop"))&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Logon Successful");&lt;br /&gt;&lt;br /&gt;            rc = true;      &lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         else&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mNotifier.Notify("Invliad User or Password");&lt;br /&gt;&lt;br /&gt;            rc = false;&lt;br /&gt;&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         return rc;&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Lets, see the new logon event handler using threads:&lt;/p&gt;&lt;pre&gt;&lt;br /&gt;      void mView_LogonEvent(object sender, EventArgs e)&lt;br /&gt;&lt;br /&gt;      {&lt;br /&gt;&lt;br /&gt;         // make sure the view is attached&lt;br /&gt;&lt;br /&gt;         Debug.Assert(mView != null, "view not attached");&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         AsyncDelegate asyncOperation = delegate&lt;br /&gt;&lt;br /&gt;         {&lt;br /&gt;&lt;br /&gt;            mView.Notify("About to perform logon");&lt;br /&gt;&lt;br /&gt;            string userName = mView.UserName;&lt;br /&gt;&lt;br /&gt;            string password = mView.Password;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            mLogonService.Logon(userName, password);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;         };&lt;br /&gt;&lt;br /&gt;         base.BeginInvoke(asyncOperation);&lt;br /&gt;&lt;br /&gt;      }&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Just one note:&lt;br /&gt;Now when you execute the program, the UI will not freeze when pressing logon (the way it should be). However that doesn't stop the user from keep pressing on the logon button. It is important to add to the view additional functions to enable and disable the button. I didn't do it in this example, however it works well with MVP, but providing a setter method to enable or disable the Logon Button.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We went a long way from our simple Logon application. We have removed most of the logic from the view, keeping the view very simple. We have used DI to allow the application to inject the controller and service into our view. Finally, I have showed a way to enable threading without making major changes. The idea is to wrap UI functions with thread safe code, allowing all UI code to be marshalled to the UI thread. The only last re-factoring left to do is to remove the thread safety wrappers, and find a way to have them done with an Advice using Spring.Net. That way we can keep the view simple, not even knowing about the threading work.&lt;br /&gt;&lt;br /&gt;However, I think this will be done in my next article. I hope you enjoyed this article - Happy .netting.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Dowload sample code: &lt;a href="http://mike.peretz.googlepages.com/MvpProject.zip"&gt;http://mike.peretz.googlepages.com/MvpProject.zip&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-3240895828231742533?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/3240895828231742533/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=3240895828231742533' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3240895828231742533'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/3240895828231742533'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2008/01/mvp.html' title='MVP (Model View Presenter or Supervising Controller) with DI (Spring.Net) and Threading support'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_cyvneGa_yo8/SDGwnZvKv3I/AAAAAAAADg4/AvV80aD4g58/s72-c/mvp.gif' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-8058306822607266776</id><published>2007-12-31T10:47:00.000-08:00</published><updated>2008-01-05T09:34:39.875-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Reflection'/><category scheme='http://www.blogger.com/atom/ns#' term='Extended Methods'/><category scheme='http://www.blogger.com/atom/ns#' term='enum reflection .net C# attributes'/><title type='text'>Attaching strings to enums</title><content type='html'>&lt;div&gt;I Found this little cool way to attach strings to enums. Using .NET 3.5 you can do something cool and simple like this&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;   public static class EnumExtension&lt;br /&gt;   {&lt;br /&gt;      public static string GetDescription(this Enum enumObj)&lt;br /&gt;      {&lt;br /&gt;         FieldInfo fieldInfo =&lt;br /&gt;         enumObj.GetType().GetField(enumObj.ToString());&lt;br /&gt;         object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;         if (attribArray.Length == 0)&lt;br /&gt;            return String.Empty;&lt;br /&gt;         else&lt;br /&gt;         {&lt;br /&gt;            DescriptionAttribute attrib =&lt;br /&gt;                attribArray[0] as DescriptionAttribute;&lt;br /&gt;            return attrib.Description;&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   class Program&lt;br /&gt;   {&lt;br /&gt;      public enum EmployeeType&lt;br /&gt;      {&lt;br /&gt;         [Description("Regular Employee")]&lt;br /&gt;         RegularEmploye,&lt;br /&gt;         [Description("Store Manager")]&lt;br /&gt;         StoreManager,&lt;br /&gt;         [Description("Chain Store Manager")]&lt;br /&gt;         ChainStoreManager,&lt;br /&gt;         [Description("Department Manager")]&lt;br /&gt;         DepartmentManager,&lt;br /&gt;         [Description("On Floor Supervisor")]&lt;br /&gt;         Supervisor&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      static void Main(string[] args)&lt;br /&gt;      {        &lt;br /&gt;         string str = EmployeeType.ChainStoreManager.GetDescription();       &lt;br /&gt;      }&lt;br /&gt;   }&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;Basically I have added an extension to the enum class to extract the value of the Description Attribute. Now, every Enum class will have a GetDescription method attached to it. This is a nice and clean way to string values out of your enums.... &lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_cyvneGa_yo8/R30MKu0dXrI/AAAAAAAACxg/C1uXHd6mSsc/s1600-h/Enum.bmp"&gt;&lt;img style="cursor:pointer; cursor:hand;" src="http://3.bp.blogspot.com/_cyvneGa_yo8/R30MKu0dXrI/AAAAAAAACxg/C1uXHd6mSsc/s400/Enum.bmp" border="0" alt=""id="BLOGGER_PHOTO_ID_5151286927288000178" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;only supported in VS2008 using .NET 3.5&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-8058306822607266776?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/8058306822607266776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=8058306822607266776' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8058306822607266776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/8058306822607266776'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/12/attaching-string-to-enums.html' title='Attaching strings to enums'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_cyvneGa_yo8/R30MKu0dXrI/AAAAAAAACxg/C1uXHd6mSsc/s72-c/Enum.bmp' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-5912374037223753282</id><published>2007-12-28T19:28:00.000-08:00</published><updated>2007-12-28T19:36:27.200-08:00</updated><title type='text'>MVP Article coming soon...</title><content type='html'>I am currently working on an article for the code project showing MVP using AOP and DI (Dependency Injection). I hope to be done before the holidays...&lt;br /&gt;&lt;br /&gt;The article will cover the following:&lt;br /&gt;&lt;br /&gt;- How to make the view unaware of the controller (using DI)&lt;br /&gt;- How to handle long running processes at the controller level&lt;br /&gt;- How to move logic outside of the controller and place it in the business layer&lt;br /&gt;- How to handle threading within the view, using AOP.&lt;br /&gt;&lt;br /&gt;Keep checking, I hope to be done within a few days...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-5912374037223753282?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/5912374037223753282/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=5912374037223753282' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5912374037223753282'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5912374037223753282'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/12/mvp-article-coming-soon.html' title='MVP Article coming soon...'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1766150308694887497</id><published>2007-11-20T16:46:00.001-08:00</published><updated>2007-11-20T16:55:07.773-08:00</updated><title type='text'>Using internal within the domain layer</title><content type='html'>There is a very nice trick you can do with the internal key word that I think is worth writing about. If you want to implement an Active Record class, such as customer.Save(), sometimes we might not want the presentation layer to have access to this method directly and pass via an application layer.&lt;br /&gt;&lt;br /&gt;so the presentation layer code will call something like this:&lt;br /&gt;&lt;pre&gt;customerService.SaveCustomer(customer) instead of customer.Save()&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The reason is that within the application layer we might want to handle error handling and logging, work that normally does not belong in the domain. With internal it is very possible. First you have to place your Customer in its own assembly. Company.Domain.dll and your presentation would be in its own assembly as well Company.Presentation.dll &lt;br /&gt;&lt;br /&gt;Now the methods and even properties you don't want the UI to access directly are marked as internal&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// Customer class&lt;br /&gt;internal Save()&lt;br /&gt;{&lt;br /&gt;   // save the information within customer&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The application layer needs to be within the same assembly as the domain, so its has access to internal members. Now our application layer can do something like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public CustomerService&lt;br /&gt;{&lt;br /&gt;     public SaveCustomer(Customer cust)&lt;br /&gt;     {&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            //delegate the work to domain, &lt;br /&gt;            //the Save method is visible to the application layer&lt;br /&gt;            cust.Save();    &lt;br /&gt;        }&lt;br /&gt;        catch(Exception e)&lt;br /&gt;        {&lt;br /&gt;             Logger.LogException(e); // perform logging &lt;br /&gt;        }&lt;br /&gt;     }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;You can even take the idea further by marking certain properties as internal, so the presentation layer will not see them at all.&lt;br /&gt;&lt;br /&gt;This is just one way of limiting the visibility of members and properties of a class, and I believe it is an elegant and nice solution when you want to control member visibility between the presentation layer and Active Record domain classes.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;One last note...&lt;/h2&gt;&lt;br /&gt;&lt;br /&gt;I am not a big fan of active record and believe more in repositories, however active record has its place in DDD, it works well when the class maps well to the persistence layer.&lt;br /&gt;&lt;br /&gt;So... remember, not everything should be public, some data should be kept "internal" to the domain.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1766150308694887497?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1766150308694887497/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1766150308694887497' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1766150308694887497'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1766150308694887497'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/using-internal-within-domain-layer.html' title='Using internal within the domain layer'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-5523092928471882586</id><published>2007-11-15T17:47:00.000-08:00</published><updated>2007-11-15T17:50:28.350-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='EndInvoke'/><title type='text'>A note about EndInvoke()</title><content type='html'>I think it is important to mention something about the &lt;code&gt;EndInvoke&lt;/code&gt;. You should know that calling EndInoke is not optional, if you don't call it there will be some sort of memory leak. Even if you don't need to know when you method finished executing, and even if there are no output parameters and return value parameters you need analyse, its a good idea to call Endinvoke. Don't forget that you will not know about exceptions if you don't call EndInvoke... so just call it...&lt;br /&gt;&lt;br /&gt;I know my fire and forget example may seem like its optional, but its not.&lt;br /&gt;&lt;br /&gt;I will also update my article to include this information.&lt;br /&gt;&lt;br /&gt;More information &lt;a href="http://www.interact-sw.co.uk/iangblog/2005/05/16/endinvokerequired"&gt;http://www.interact-sw.co.uk/iangblog/2005/05/16/endinvokerequired&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-5523092928471882586?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/5523092928471882586/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=5523092928471882586' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5523092928471882586'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/5523092928471882586'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/note-about-endinvoke.html' title='A note about EndInvoke()'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-1824350127160818488</id><published>2007-11-13T18:55:00.000-08:00</published><updated>2007-11-13T19:04:33.847-08:00</updated><title type='text'>Coming soon...</title><content type='html'>&lt;h3&gt;Locking objects at the application layer&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;How to implement pessimistic locking without using a database or a data access layer. Providing the management to "check-out", "check-in" objects at the application layer.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Plug-ins&lt;/h3&gt;&lt;br /&gt;How to build a dynamic winform application using plug-in design&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Model View Presenter with Async method invocation&lt;/h3&gt;&lt;br /&gt;How to use Model View Presenter design pattern, with async method invocation to never freeze the UI and create a flexible user interface.&lt;br /&gt;&lt;br /&gt;As soon as I have a little time (between changing diapers)... I will write down all these juicy articles.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-1824350127160818488?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/1824350127160818488/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=1824350127160818488' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1824350127160818488'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/1824350127160818488'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/coming-soon.html' title='Coming soon...'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-2700024751849576410</id><published>2007-11-13T18:40:00.000-08:00</published><updated>2007-11-13T18:49:33.221-08:00</updated><title type='text'>.NET Links</title><content type='html'>&lt;strong&gt;My .NET Links Collection&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;Web casts and videos&lt;/span&gt;&lt;br /&gt;&lt;a href="http://www.dotnetrocks.com/"&gt;.NET Rocks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://channel9.msdn.com/tags/Architecture"&gt;Channel 9&lt;/a&gt;&lt;br /&gt;&lt;a href="http://wcf.netfx3.com/"&gt;NetFX&lt;/a&gt;&lt;br /&gt;&lt;a href="http://wf.netfx3.com/"&gt;Windows Workflow&lt;/a&gt;&lt;br /&gt;&lt;a href="http://wpf.netfx3.com/"&gt;Windows Presentation Foundation&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-2700024751849576410?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/2700024751849576410/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=2700024751849576410' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2700024751849576410'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2700024751849576410'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/net-links.html' title='.NET Links'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-4027462133369737058</id><published>2007-11-12T15:48:00.000-08:00</published><updated>2007-11-12T15:50:17.851-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C# .net compoiste design patterns'/><title type='text'>Logging Using the Composite Pattern</title><content type='html'>&lt;!----------------------------- Article Starts -----------------------------&gt;&lt;br /&gt;&lt;UL class=download&gt;&lt;br /&gt;&lt;LI&gt;&lt;A href="http://www.codeproject.com/cs/design/CompositePattern/LoggerExample.zip"&gt;Download source code - 48.4 Kb&lt;/A&gt; &lt;/LI&gt;&lt;/UL&gt;&lt;br /&gt;&lt;H2&gt;Introduction&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;In this article, I will explain how I solved a common problem I used to have regarding logging within my business layer. Normally, I would have a function call from my presentation layer to my business layer; however, once in the business layer, I had no access to the presentation layer anymore. There are many ways to solve this problem. In the MFC days, a Doc / View approach based on the Observer pattern was used. In .NET, we can use custom events to notify the presentation layer that something happened. But, in this article, I will show the Composite pattern in action, and some of its nice advantages.&lt;/P&gt;&lt;br /&gt;&lt;H2&gt;The Requirements&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Suppose we had a function in our business layer that performs a lot of updates. It would be nice that during all these updates, we log the exact action taking place. We want to easily log a string describing the activity to one of, all of, or some of the following loggers: &lt;CODE&gt;TextBox&lt;/CODE&gt;, &lt;CODE&gt;ListBox&lt;/CODE&gt;, text file and/or the EventLog.&lt;/P&gt;&lt;br /&gt;&lt;H2&gt;Creating the ILogger Interface&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;To keep the example simple, I will implement a simple &lt;CODE&gt;ILogger&lt;/CODE&gt; interface that only requires a logger class to implement its own way of logging an activity.&lt;/P&gt;&lt;PRE lang=cs&gt;public interface ILogger&lt;br /&gt;{&lt;br /&gt;    void LogMessage(string strMessage);&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Creating Logger Classes&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Create the following logger classes:&lt;/P&gt;&lt;br /&gt;&lt;UL&gt;&lt;br /&gt;&lt;LI&gt;Text box logger - logs a message into a text box &lt;br /&gt;&lt;LI&gt;List box logger - adds a message to the list &lt;br /&gt;&lt;LI&gt;File logger - logs a message into a file &lt;br /&gt;&lt;LI&gt;EventLog logger - logs a message into the system event log &lt;/LI&gt;&lt;/UL&gt;&lt;br /&gt;&lt;H2&gt;ListBox Logger&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Notice that the &lt;CODE&gt;ListBox&lt;/CODE&gt; and &lt;CODE&gt;TextBox&lt;/CODE&gt; loggers are thread safe, by using the &lt;CODE&gt;InvokeRequired&lt;/CODE&gt; method.&lt;/P&gt;&lt;PRE lang=cs&gt;class ListBoxLogger : ILogger&lt;br /&gt;{&lt;br /&gt;    ListBox m_listBox;&lt;br /&gt;    public ListBoxLogger(ListBox listBox)&lt;br /&gt;    {&lt;br /&gt;        m_listBox = listBox;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void LogMessage(string strMessage)&lt;br /&gt;    {&lt;br /&gt;        MethodInvoker logDelegate = delegate &lt;br /&gt;        {&lt;br /&gt;            m_listBox.Items.Add(strMessage);&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        if (m_listBox.InvokeRequired)&lt;br /&gt;            m_listBox.Invoke(logDelegate);&lt;br /&gt;        else&lt;br /&gt;            logDelegate();&lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;TextBox Logger&lt;/H2&gt;&lt;PRE lang=cs&gt;class TextBoxLogger : ILogger&lt;br /&gt;{&lt;br /&gt;    private TextBox m_textBox;&lt;br /&gt;    public TextBoxLogger(TextBox txtBox)&lt;br /&gt;    {&lt;br /&gt;        m_textBox = txtBox;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void LogMessage(string strLogMessage)&lt;br /&gt;    {&lt;br /&gt;        MethodInvoker logDelegate = delegate { m_textBox.Text = strLogMessage; };&lt;br /&gt;        if (m_textBox.InvokeRequired)&lt;br /&gt;            m_textBox.Invoke(logDelegate);&lt;br /&gt;        else&lt;br /&gt;            logDelegate();&lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;File Logger&lt;/H2&gt;&lt;PRE lang=cs&gt;class FileLogger : ILogger&lt;br /&gt;{&lt;br /&gt;    private string m_strFileName;&lt;br /&gt;    private object m_sync = new object();&lt;br /&gt;    public FileLogger(string strFileName)&lt;br /&gt;    {&lt;br /&gt;        m_strFileName = strFileName;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void LogMessage(string strMessage)&lt;br /&gt;    {&lt;br /&gt;        lock (m_sync)&lt;br /&gt;        {&lt;br /&gt;            using (StreamWriter writer = new StreamWriter(m_strFileName))&lt;br /&gt;            {&lt;br /&gt;                writer.WriteLine(strMessage);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;P&gt;Notice that the &lt;CODE&gt;FileLogger&lt;/CODE&gt; is thread-safe, and that it opens and closes the file before writing to it. This guarantees that the message is flushed after each call to &lt;CODE&gt;LogMessage&lt;/CODE&gt;.&lt;/P&gt;&lt;br /&gt;&lt;H2&gt;EventLog Logger&lt;/H2&gt;&lt;PRE lang=cs&gt;class EventLogger : ILogger&lt;br /&gt;{&lt;br /&gt;    public EventLogger()&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void LogMessage(string strMessage)&lt;br /&gt;    {&lt;br /&gt;        EventLog.WriteEntry("Logger", strMessage);&lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Using the ILogger Object&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;So far, there is nothing special here; we can have a function that takes a &lt;CODE&gt;ILogger&lt;/CODE&gt; object and allow us to log messages. For example:&lt;/P&gt;&lt;PRE lang=cs&gt;private void DoSomthing(ILogger logger)&lt;br /&gt;{&lt;br /&gt;    for(int i=0; i &amp;lt; 10; i++)&lt;br /&gt;    {&lt;br /&gt;        logger.LogMessage("Logging a message " + i.ToString());&lt;br /&gt;     &lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;P&gt;The client code looks like this:&lt;/P&gt;&lt;PRE lang=cs&gt;// pass the File Logger&lt;br /&gt;DoSomthing(new FileLogger("C://LogMessage.txt")); &lt;br /&gt;// txtBox is a text box control on the form&lt;br /&gt;DoSomthing(new TextBoxLogger(textBox));&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Introducing the CompositeLogger&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;But what if I want to log to all my loggers at the same time, or what if I want to log to only some of my loggers? To solve this requirement, I create a new logger called a Composite Logger.&lt;/P&gt;&lt;PRE lang=cs&gt;// Logger of composite of loggers&lt;br /&gt;class CompositeLogger : ILogger&lt;br /&gt;{&lt;br /&gt;    private ILogger[] m_loggerArray;&lt;br /&gt;    &lt;br /&gt;    // pass a ILoggers that are part of this composite logger&lt;br /&gt;    public CompositeLogger(params ILogger[] loggers)&lt;br /&gt;    {&lt;br /&gt;        m_loggerArray = loggers;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void LogMessage(string strMessage)&lt;br /&gt;    {&lt;br /&gt;        // loop around all the loggers, and log the message.&lt;br /&gt;        foreach (ILogger logger in m_loggerArray)&lt;br /&gt;            logger.LogMessage(strMessage);&lt;br /&gt;    }&lt;br /&gt;}&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Let's Use Our Composite Logger to "Configure" Which Loggers to Use&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Using all the loggers:&lt;/P&gt;&lt;PRE lang=cs&gt;CompositeLogger compositeLogger =   &lt;br /&gt;        new CompositeLogger(new TextBoxLogger(textBox),&lt;br /&gt;                            new ListBoxLogger(listBox),&lt;br /&gt;                            new FileLogger("C:\\LogPattern.txt"),&lt;br /&gt;                            new EventLogger() );&lt;/PRE&gt;&lt;br /&gt;&lt;P&gt;Creating a composite logger with only &lt;CODE&gt;TextBoxLogger&lt;/CODE&gt; and &lt;CODE&gt;ListBoxLogger&lt;/CODE&gt;:&lt;/P&gt;&lt;PRE lang=cs&gt;CompositeLogger compositeLogger =   &lt;br /&gt;        new CompositeLogger(new TextBoxLogger(textBox),&lt;br /&gt;                            new ListBoxLogger(listBox));&lt;/PRE&gt;&lt;br /&gt;&lt;P&gt;Because our composite logger implements &lt;CODE&gt;ILogger&lt;/CODE&gt; like all the other loggers, we can pass it to a function that expects an &lt;CODE&gt;ILogger&lt;/CODE&gt; object type.&lt;/P&gt;&lt;PRE lang=cs&gt;DoSomthing(compositeLogger);&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Testing the Composite Logger in a Thread&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Let’s test our composite logger in a separate thread, just to make sure we can update the UI from a thread other than the UI-thread.&lt;/P&gt;&lt;PRE lang=cs&gt;// create a composite logger with all the loggers&lt;br /&gt;CompositeLogger compositeLogger =&lt;br /&gt;    new CompositeLogger(&lt;br /&gt;            new TextBoxLogger(textBox),&lt;br /&gt;            new ListBoxLogger(listBox),&lt;br /&gt;            new FileLogger("C:\\LogPattern.txt"),&lt;br /&gt;            new EventLogger());&lt;br /&gt;&lt;br /&gt;// create a anonymous function to call DoSomthing&lt;br /&gt;ParameterizedThreadStart threadDelegate = delegate(object obj)&lt;br /&gt;{&lt;br /&gt;    ILogger logger = (ILogger)obj;&lt;br /&gt;    DoSomthing(logger);&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// Do Somthing in a thread&lt;br /&gt;Thread t = new Thread(threadDelegate);&lt;br /&gt;t.Start(compositeLogger);&lt;/PRE&gt;&lt;br /&gt;&lt;H2&gt;Conclusion&lt;/H2&gt;&lt;br /&gt;&lt;P&gt;Notice that I am now able to pass an &lt;CODE&gt;ILogger&lt;/CODE&gt; object to a method within the business layer or to the data layer, and provide an easy way to log a message. This is done by using the &lt;CODE&gt;ILogger&lt;/CODE&gt; interface, and therefore, your business layer or data layer requires no extra references to &lt;CODE&gt;File.Io&lt;/CODE&gt;, or &lt;CODE&gt;Windows.Forms&lt;/CODE&gt;, it only needs to have a reference to &lt;CODE&gt;ILogger&lt;/CODE&gt;. It is also nice that you can easily add and remove loggers by using your composite Logger. Thank you for reading, have a good day!&lt;/P&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;!----------------------------- Article Ends -----------------------------&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-4027462133369737058?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/4027462133369737058/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=4027462133369737058' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4027462133369737058'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/4027462133369737058'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/logging-using-composite-pattern.html' title='Logging Using the Composite Pattern'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-2427189711683180052</id><published>2007-11-12T15:41:00.000-08:00</published><updated>2007-11-12T15:46:42.086-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='enum reflection .net C# attributes'/><title type='text'>.NET Enum The Next Level</title><content type='html'>&lt;H2&gt;Introduction&lt;/H2&gt;&lt;br /&gt;&lt;p&gt;In this article, I am going to explore enums a little further. I am not going to cover the basic information about enums (you can always refer to MSDN for details). My biggest beef with enum is that it only represents numeric data. It is flexible to represent different integral types, but it can not hold a string. Enums do support the &lt;code&gt;ToString()&lt;/code&gt; function, however with limitation (I will go into it in more details, later in the article). Basically, I want to be able to make my enumeration element be associated to more than just an integer value, to achieve this I will use Reflection and Attributes and try to keep my example as simple as possible. &lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Using ToString() with enums&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Let's create a simple enumeration... &lt;/p&gt;&lt;pre lang="cs"&gt;    public enum EmployeeType&lt;br /&gt;    {&lt;br /&gt;        RegularEmployee,&lt;br /&gt;        StoreManager,&lt;br /&gt;        ChainStoreManager,&lt;br /&gt;        DepartmentManager,&lt;br /&gt;        Supervisor&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Based on this simple plain vanilla enumeration, we can get the following information: a &lt;code&gt;String&lt;/code&gt; representation using &lt;code&gt;ToString()&lt;/code&gt;. &lt;/p&gt;&lt;pre lang="cs"&gt;   EmployeeType employee = EmployeeType.ChainStoreManager;&lt;br /&gt;   Console.WriteLine(employee.ToString());&lt;br /&gt;   Console.WriteLine(EmployeeType.ChainStoreManager.ToString());&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The output is the same for both lines of code: &lt;/p&gt;&lt;pre lang="text"&gt;ChainStoreManager&lt;br /&gt;ChainStoreManager&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;But what if I wanted to get "&lt;strong&gt;Chain Store Manager&lt;/strong&gt;" with spaces? You can not create an enum type that contains spaces, your code wouldn't compile. There are a lot of solutions to this problem.&lt;/p&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Create a mapping between enums and strings (using arrays, or hashtables).&lt;br /&gt;&lt;li&gt;Using the enum &lt;code&gt;ToString()&lt;/code&gt; as a key for a language resource file.&lt;br /&gt;&lt;li&gt;Use a litte bit of reflection... I will explore option 3... &lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;h2&gt;Using attributes with enums&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;In order to associate a string with an enumeration, I used Attributes. I will start with a simple exmaple that will assocate my enumeration with a string. &lt;/p&gt;&lt;pre lang="cs"&gt;    public class EnumDescriptionAttribute : Attribute&lt;br /&gt;    {&lt;br /&gt;        private string m_strDescription;&lt;br /&gt;        public EnumDescriptionAttribute(string strPrinterName)&lt;br /&gt;        {&lt;br /&gt;            m_strDescription = strPrinterName;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string Description&lt;br /&gt;        {&lt;br /&gt;            get { return m_strDescription; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;code&gt;EnumDescriptionAttribute&lt;/code&gt; is a simple attribute that holds a string. The attribute has a single property to return the description. For now, I am going to keep it as simple as possible. Now that I have my description attribute, I will assocate it with each enum element.&lt;/p&gt;&lt;pre lang="cs"&gt;public enum EmployeeType&lt;br /&gt;{&lt;br /&gt;    &lt;strong&gt;[EnumDescription("Regular Employee")]&lt;/strong&gt;&lt;br /&gt;    RegularEmploye,&lt;br /&gt;    &lt;strong&gt;[EnumDescription("Store Manager")]&lt;/strong&gt;&lt;br /&gt;    StoreManager,&lt;br /&gt;    &lt;strong&gt;[EnumDescription("Chain Store Manager")]&lt;/strong&gt;&lt;br /&gt;    ChainStoreManager,&lt;br /&gt;    &lt;strong&gt;[EnumDescription("Department Manager")]&lt;/strong&gt;&lt;br /&gt;    DepartmentManager,&lt;br /&gt;    &lt;strong&gt;[EnumDescription("On Floor Supervisor")]&lt;/strong&gt;&lt;br /&gt;    Supervisor&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;Getting the attribute value from an enum&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;In order to get the attribute value from an enumeration, I have to use Reflection. Here is an example:&lt;/p&gt;&lt;pre lang="cs"&gt;// setup the enum&lt;br /&gt;EmployeeType employee = EmployeeType.ChainStoreManager;&lt;br /&gt;&lt;br /&gt;// get the field informaiton&lt;br /&gt;FieldInfo fieldInfo = employee.GetType().GetField("ChainStoreManager");&lt;br /&gt;&lt;br /&gt;// get the attributes for the enum field&lt;br /&gt;object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;&lt;br /&gt;// cast the one and only attribute to EnumDescriptionAttribute&lt;br /&gt;EnumDescriptionAttribute attrib =&lt;br /&gt;    (EnumDescriptionAttribute)attribArray[0];&lt;br /&gt;&lt;br /&gt;// write the description&lt;br /&gt;console.WriteLine("Description: {0}", attrib.Description);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Output: Chain Store Manager&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The most important line of code is: &lt;code&gt;FieldInfo fieldInfo = employee.GetType().GetField("ChainStoreManager");&lt;/code&gt;. Notice that I hardcoded the enum element name &lt;em&gt;ChainStoreManager&lt;/em&gt;, but if you go back and look at the &lt;code&gt;ToString()&lt;/code&gt; function, you can see that I could have used &lt;code&gt;ToString()&lt;/code&gt; instead. &lt;/p&gt;&lt;br /&gt;&lt;h2&gt;A Generic function to get the description &lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Notice I used &lt;code&gt;ToString()&lt;/code&gt; on the Enum...&lt;/p&gt;&lt;pre lang="cs"&gt;public static string GetEnumDescription(Enum enumObj)&lt;br /&gt;{&lt;br /&gt;    FieldInfo fieldInfo =&lt;br /&gt;        enumObj.GetType().GetField(enumObj.ToString());&lt;br /&gt;&lt;br /&gt;    object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;    if (attribArray.Length == 0)&lt;br /&gt;        return String.Empty;&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        EnumDescriptionAttribute attrib =&lt;br /&gt;            attribArray[0] as EnumDescriptionAttribute;&lt;br /&gt;&lt;br /&gt;        return attrib.Description;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;h2&gt;Let's associate more than just a string to our enum elements&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;So far, we only associated a description to our enumeration element. However, it is fully possible to associate any type of data to our enum. To show this, I am going to create a new enumeration (similar to the first one). &lt;/p&gt;&lt;pre lang="cs"&gt;public enum ManagerType&lt;br /&gt;{&lt;br /&gt;    StoreManager,&lt;br /&gt;    ChainManager,&lt;br /&gt;    Superivor&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;I am also creating a new attribute class, &lt;code&gt;ManagerAttribute&lt;/code&gt;, that inherits from &lt;code&gt;EnumDescription&lt;/code&gt;, and provides two additional pieces of information (Min Salary and Max Salary).&lt;/p&gt;&lt;pre lang="cs"&gt;public class ManagerAttribute : EnumDescriptionAttribute&lt;br /&gt;{&lt;br /&gt;    private int m_intMinSalary;&lt;br /&gt;    private int m_intMaxSalary;&lt;br /&gt;    public ManagerAttribute(string strDescription,&lt;br /&gt;        int intMinSalary,&lt;br /&gt;        int intMaxSalary) : base(strDescription)&lt;br /&gt;    {&lt;br /&gt;        m_intMinSalary = intMinSalary;&lt;br /&gt;        m_intMaxSalary = intMaxSalary;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public ManagerAttribute(string strDescription)&lt;br /&gt;        : base(strDescription)&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public int MinSalary&lt;br /&gt;    {&lt;br /&gt;        get {return m_intMinSalary;}&lt;br /&gt;        set { m_intMinSalary = value; }&lt;br /&gt;    }&lt;br /&gt;    public int MaxSalary&lt;br /&gt;    {&lt;br /&gt;        get { return m_intMaxSalary;}&lt;br /&gt;        set { m_intMaxSalary = value; }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now, I am going to associate a &lt;code&gt;ManagerAttribute&lt;/code&gt; to each enum element. Notice that I am using the &lt;code lang="cs"&gt;set&lt;/code&gt; properties within my &lt;code&gt;ManagerAttribute&lt;/code&gt;s, so the code is more readable &lt;/p&gt;&lt;pre lang="cs"&gt;public enum ManagerType&lt;br /&gt;{&lt;br /&gt;    [Manager("Store Manager", MinSalary=40000, MaxSalary=100000)]&lt;br /&gt;    StoreManager,&lt;br /&gt;    [Manager("Chain Manager", MinSalary=50000, MaxSalary=110000)]&lt;br /&gt;    ChainManager,&lt;br /&gt;    [Manager("Store Supervisor", MinSalary=30000, MaxSalary=50000)]&lt;br /&gt;    Superivor&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Next step is improving our generic function to allow us to get any type of &lt;code&gt;EnumDescriptionAttribute&lt;/code&gt;; using Generics this is easily done! &lt;/p&gt;&lt;pre lang="cs"&gt;public static T GetAttribute&amp;lt;T&amp;gt;(Enum enumObj) where T : EnumDescriptionAttribute&lt;br /&gt;{&lt;br /&gt;    // get field informaiton for our enum element&lt;br /&gt;    FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());&lt;br /&gt;&lt;br /&gt;    // get all the attributes associated with our enum&lt;br /&gt;    object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;&lt;br /&gt;    if (attribArray.Length == 0)&lt;br /&gt;        return default(T);&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        // cast the attribute and return it&lt;br /&gt;        T attrib = (T)attribArray[0];&lt;br /&gt;        if (attrib != null)&lt;br /&gt;            return attrib;&lt;br /&gt;        else&lt;br /&gt;            return default(T);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;Helper functions&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;So far we have got two helper functions, one to obtain a simple string description of an enum, and the other function, a more generic function to obtain any attribute that inherits from &lt;code&gt;EnumDescriptionAttribute&lt;/code&gt;. You can add these helper functions to a class like &lt;code&gt;EnumHelper&lt;/code&gt;; but in this example, I decided to simply add them to the existing &lt;code&gt;EnumDescriptionAttribute&lt;/code&gt;. &lt;/p&gt;&lt;pre lang="cs"&gt;public class EnumDescriptionAttribute : Attribute&lt;br /&gt;{&lt;br /&gt;    private string m_strDescription;&lt;br /&gt;    public EnumDescriptionAttribute(string strEnumDescription)&lt;br /&gt;    {&lt;br /&gt;        m_strDescription = strEnumDescription;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string Description { get { return m_strDescription; } }&lt;br /&gt;&lt;br /&gt;    public static string GetEnumDescription(Enum enumObj)&lt;br /&gt;    {&lt;br /&gt;        FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());&lt;br /&gt;        object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;        if (attribArray.Length == 0)&lt;br /&gt;            return String.Empty;&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            EnumDescriptionAttribute attrib = attribArray[0]&lt;br /&gt;                as EnumDescriptionAttribute;&lt;br /&gt;&lt;br /&gt;            return attrib.Description;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    public static T GetAttribute&amp;lt;T&amp;gt;(Enum enumObj)&lt;br /&gt;        where T : EnumDescriptionAttribute&lt;br /&gt;    {&lt;br /&gt;        FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());&lt;br /&gt;        object[] attribArray = fieldInfo.GetCustomAttributes(false);&lt;br /&gt;        if (attribArray.Length == 0)&lt;br /&gt;            return default(T);&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            T attrib = (T)attribArray[0];&lt;br /&gt;            if (attrib != null)&lt;br /&gt;                return attrib;&lt;br /&gt;            else&lt;br /&gt;                return default(T);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;Finally... Let's see it all together&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;To get a string description, we can simple code this: &lt;pre lang="cs"&gt;string desc =&lt;br /&gt;    EnumDescriptionAttribute.GetEnumDescription(EmployeeType.DepartmentManager);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To get a &lt;code&gt;ManagerAttribute&lt;/code&gt;, we can code this: &lt;/p&gt;&lt;pre lang="cs"&gt;ManagerAttribute manager =&lt;br /&gt;    EnumDescriptionAttribute.GetAttribute&amp;lt;ManagerAttribute&amp;gt;(&lt;br /&gt;    EmployeeType.DepartmentManager);&lt;br /&gt;&lt;br /&gt;Console.WriteLine("Manager: {0}, Min Salary: {1}, Max Salary {2}",&lt;br /&gt;    attrib.Description,&lt;br /&gt;    manager.MinSalary,&lt;br /&gt;    manager.MaxSalary);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now you can see that you can use attributes to associate addtional information to an element of an enum. &lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Okay, so you can see that it is not hard to associate additional information to your enumeration element by simply using some attributes and reflection. However, it is important to note that I do not believe attributes should replace common business objects. I simply wanted to show that an enum does not have to only represent an integral value. As you read in this article, you can associate your enum to a string or any other class. One of the nice advantages of using attributes is that it is easy to implement and it makes the code readable. You can see how readable the &lt;code&gt;ManagerType&lt;/code&gt; enumeration is with the implementation of the &lt;code&gt;ManagerAttribute&lt;/code&gt;. It is easy to know exactly what each enumeration item contains. I hope you enjoyed reading this article, and I welcome all comments or questions about it. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-2427189711683180052?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/2427189711683180052/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=2427189711683180052' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2427189711683180052'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/2427189711683180052'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/please-choose-view-source-in-your.html' title='.NET Enum The Next Level'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9202309254227413537.post-386131875390359264</id><published>2007-11-12T09:55:00.000-08:00</published><updated>2007-11-12T15:29:36.375-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Asynchronous Method Invocation Thread UI Invoke BeginInvoke Control'/><title type='text'>Asynchronous Method Invocation</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;p&gt;In this article, I am going to explain asynchronous method calls and how to use them. After playing with delegates, threads, and asynchronous invocation for so long, it would be a sin not to share some of my wisdom and knowledge on the subject, so hopefully, you won’t be looking at an MSDN article at 1 AM wondering why you decided to go into computers. I will try to use baby steps and lots of examples… Overall, I will cover how to call methods asynchronously, how to pass parameters to such methods, and how to find out when a method completes execution. Finally, I will show the Command Pattern in use for simplifying some of the code. The big advantage with .NET asynchronous method invocation is that you can take any method you have in your project, and you can call it asynchronously without touching the code of your method. Although most of the magic is within the .NET framework, it is important to see what is going on in the back, and that’s what we are going to study here.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Synchronous vs. Asynchronous&lt;/h2&gt;&lt;p&gt;Let me try to explain synchronous and asynchronous method invocations with an example, because I know people on The Code Project like to see code and not read War and Peace (not that I have anything against this book). &lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Synchronous method invocation&lt;/h3&gt;&lt;p&gt;Suppose we have a function &lt;code&gt;Foo()&lt;/code&gt; that takes 10 seconds to execute.&lt;/p&gt;&lt;pre lang="cs"&gt;private void Foo()&lt;br /&gt;{&lt;br /&gt;    // sleep for 10 seconds.&lt;br /&gt;    Thread.Sleep(10000);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Normally, when your application calls the function &lt;code&gt;Foo()&lt;/code&gt;, it will need to wait 10 seconds until &lt;code&gt;Foo()&lt;/code&gt; is finished and control is returned to the calling thread. Now, suppose you want to call &lt;code&gt;Foo()&lt;/code&gt; 100 times, then we know that it would take 1000 seconds for the control to return to the calling thread. This type of a method invocation is Synchronous.&lt;/p&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Call &lt;code&gt;Foo()&lt;/code&gt;&lt;br /&gt;&lt;li&gt;&lt;code&gt;Foo()&lt;/code&gt; is executed&lt;br /&gt;&lt;li&gt;Control goes back to the calling thread &lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;p&gt;Let's now call &lt;code&gt;Foo()&lt;/code&gt; using delegates because most of the work we will do here is based on delegates. Luckily for us, there is already a delegate within the .NET framework that allows us to call a function that takes no parameter and has no return value. The delegate is called &lt;code&gt;MethodeInvoker&lt;/code&gt;. Let's play with it a little.&lt;/p&gt;&lt;pre lang="cs"&gt;// create a delegate of MethodInvoker poiting&lt;br /&gt;// to our Foo() function.&lt;br /&gt;MethodInvoker simpleDelegate = new MethodInvoker(Foo);&lt;br /&gt;&lt;br /&gt;// Calling Foo&lt;br /&gt;simpleDelegate.Invoke();&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Even with the example above, we are still calling &lt;code&gt;Foo()&lt;/code&gt; synchronously. The calling thread still needs to wait for the &lt;code&gt;Invoke()&lt;/code&gt; function to complete until the control is returned to the calling thread.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Asynchronous method invocation&lt;/h3&gt;&lt;p&gt;But what if I wanted to call &lt;code&gt;Foo()&lt;/code&gt; and not wait for it to finish executing? In fact, to make things interesting, what if I didn’t care when it is finished? Let’s say, I just wanted to call &lt;code&gt;Foo&lt;/code&gt; 100 times without waiting for any of the function calls to complete. Basically, doing something called &lt;i&gt;Fire and Forget&lt;/i&gt;. You call the function, you don’t wait for it, and you just forget about it. And… let’s not forget! I am not willing to change a line of code in my super complicated fancy &lt;code&gt;Foo()&lt;/code&gt; function.&lt;/p&gt;&lt;pre lang="cs"&gt;// create a delegate of MethodInvoker poiting to&lt;br /&gt;// our Foo function.&lt;br /&gt;MethodInvoker simpleDelegate = new MethodInvoker(Foo);&lt;br /&gt;&lt;br /&gt;// Calling Foo Async&lt;br /&gt;for(int i=0; i&amp;lt;100; i++)&lt;br /&gt;    simpleDelegate.BeginInvoke(null, null);&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let me make a few comments about the code above.&lt;/p&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Notice that &lt;code&gt;BeginInvoke()&lt;/code&gt; is the line of code that executes the &lt;code&gt;Foo()&lt;/code&gt; function. However, the control is returned to the caller right away, without waiting for &lt;code&gt;Foo()&lt;/code&gt; to complete.&lt;br /&gt;&lt;li&gt;The code above does not know when a call to &lt;code&gt;Foo()&lt;/code&gt; completes, I will cover that later.&lt;br /&gt;&lt;li&gt;&lt;code&gt;BeginInvoke()&lt;/code&gt; is used instead of &lt;code&gt;Invoke()&lt;/code&gt;. For now, don’t worry about the parameters this function takes; I will cover that in more detail later. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;What is the magic that .NET is doing in the background&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Once you ask the framework to call something asynchronously, it needs a thread to do the work. It can not be the current thread, because that would make the invocation synchronous (blocking). Instead, the runtime queues a request to execute the function on a thread from the &lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconThreadPooling.asp" target="_blank"&gt;.NET Thread Pool&lt;/a&gt;. You don’t really need to code anything for it, all of it happens in the background. But, just because it is all transparent doesn’t mean you should care about it. There are a few things to remember:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;code&gt;Foo()&lt;/code&gt; is executed on a separate thread, a thread that belongs to the .NET Thread Pool.&lt;br /&gt;&lt;li&gt;A .NET Thread Pool normally has 25 threads in it (you can change that limit), and each time &lt;code&gt;Foo()&lt;/code&gt; is called, it is going to be executed on one of these threads. You can't control which one.&lt;br /&gt;&lt;li&gt;The Thread Pool has its limits! Once all the threads are used, an async method invocation is queued until one of the threads from the pool is freed. This is called &lt;b&gt;Thread Pool Starvation&lt;/b&gt;, and normally when it comes to that, performance is compromised. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;Don’t dive too deep into the thread pool, you might run out of oxygen!&lt;/h2&gt;&lt;p&gt;So, let's see an example of when the Thread Pool is starved. Let's modify our &lt;code&gt;Foo&lt;/code&gt; function to wait for 30 seconds, and also let it report the following:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Number of avaible threads on the pool &lt;li&gt;If the thread is on the thread pool &lt;li&gt;The thread ID. &lt;/li&gt;&lt;/ul&gt;&lt;p&gt;We know that initially the thread pool contains 25 threads, so I am going to call my &lt;code&gt;Foo&lt;/code&gt; function asynchronously 30 times (to see what happens after the 25&lt;sup&gt;th&lt;/sup&gt; call).&lt;/p&gt;&lt;pre lang="cs"&gt;private void CallFoo30AsyncTimes()&lt;br /&gt;{&lt;br /&gt;    // create a delegate of MethodInvoker&lt;br /&gt;    // poiting to our Foo function.&lt;br /&gt;    MethodInvoker simpleDelegate =&lt;br /&gt;        new MethodInvoker(Foo);&lt;br /&gt;&lt;br /&gt;    // Calling Foo Async 30 times.&lt;br /&gt;    for (int i = 0; i &amp;lt; 30; i++)&lt;br /&gt;    {&lt;br /&gt;         // call Foo()&lt;br /&gt;        simpleDelegate.BeginInvoke(null, null);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;pre lang="cs"&gt;private void Foo()&lt;br /&gt;{&lt;br /&gt;    int intAvailableThreads, intAvailableIoAsynThreds;&lt;br /&gt;&lt;br /&gt;    // ask the number of avaialbe threads on the pool,&lt;br /&gt;    //we really only care about the first parameter.&lt;br /&gt;    ThreadPool.GetAvailableThreads(out intAvailableThreads,&lt;br /&gt;            out intAvailableIoAsynThreds);&lt;br /&gt;&lt;br /&gt;    // build a message to log&lt;br /&gt;    string strMessage =&lt;br /&gt;        String.Format(@"Is Thread Pool: {1},&lt;br /&gt;            Thread Id: {2} Free Threads {3}",&lt;br /&gt;            Thread.CurrentThread.IsThreadPoolThread.ToString(),&lt;br /&gt;            Thread.CurrentThread.GetHashCode(),&lt;br /&gt;            intAvailableThreads);&lt;br /&gt;&lt;br /&gt;    // check if the thread is on the thread pool.&lt;br /&gt;    Trace.WriteLine(strMessage);&lt;br /&gt;&lt;br /&gt;    // create a delay...&lt;br /&gt;    Thread.Sleep(30000);&lt;br /&gt;&lt;br /&gt;    return;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Output window:&lt;/p&gt;&lt;pre lang="text"&gt;Is Thread Pool: True, Thread Id: 7 Free Threads 24&lt;br /&gt;Is Thread Pool: True, Thread Id: 12 Free Threads 23&lt;br /&gt;Is Thread Pool: True, Thread Id: 13 Free Threads 22&lt;br /&gt;Is Thread Pool: True, Thread Id: 14 Free Threads 21&lt;br /&gt;Is Thread Pool: True, Thread Id: 15 Free Threads 20&lt;br /&gt;Is Thread Pool: True, Thread Id: 16 Free Threads 19&lt;br /&gt;Is Thread Pool: True, Thread Id: 17 Free Threads 18&lt;br /&gt;Is Thread Pool: True, Thread Id: 18 Free Threads 17&lt;br /&gt;Is Thread Pool: True, Thread Id: 19 Free Threads 16&lt;br /&gt;Is Thread Pool: True, Thread Id: 20 Free Threads 15&lt;br /&gt;Is Thread Pool: True, Thread Id: 21 Free Threads 14&lt;br /&gt;Is Thread Pool: True, Thread Id: 22 Free Threads 13&lt;br /&gt;Is Thread Pool: True, Thread Id: 23 Free Threads 12&lt;br /&gt;Is Thread Pool: True, Thread Id: 24 Free Threads 11&lt;br /&gt;Is Thread Pool: True, Thread Id: 25 Free Threads 10&lt;br /&gt;Is Thread Pool: True, Thread Id: 26 Free Threads 9&lt;br /&gt;Is Thread Pool: True, Thread Id: 27 Free Threads 8&lt;br /&gt;Is Thread Pool: True, Thread Id: 28 Free Threads 7&lt;br /&gt;Is Thread Pool: True, Thread Id: 29 Free Threads 6&lt;br /&gt;Is Thread Pool: True, Thread Id: 30 Free Threads 5&lt;br /&gt;Is Thread Pool: True, Thread Id: 31 Free Threads 4&lt;br /&gt;Is Thread Pool: True, Thread Id: 32 Free Threads 3&lt;br /&gt;Is Thread Pool: True, Thread Id: 33 Free Threads 2&lt;br /&gt;Is Thread Pool: True, Thread Id: 34 Free Threads 1&lt;br /&gt;Is Thread Pool: True, Thread Id: 35 Free Threads 0&lt;br /&gt;Is Thread Pool: True, Thread Id: 7 Free Threads 0&lt;br /&gt;Is Thread Pool: True, Thread Id: 12 Free Threads 0&lt;br /&gt;Is Thread Pool: True, Thread Id: 13 Free Threads 0&lt;br /&gt;Is Thread Pool: True, Thread Id: 14 Free Threads 0&lt;br /&gt;Is Thread Pool: True, Thread Id: 15 Free Threads 0&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let’s make a few notes about the output:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Notice, first of all, that all the threads are on the thread pool.&lt;br /&gt;&lt;li&gt;Notice that each time &lt;code&gt;Foo&lt;/code&gt; is called, another thread ID is assigned. However, you can see that some of the threads are recycled.&lt;br /&gt;&lt;li&gt;After calling &lt;code&gt;Foo()&lt;/code&gt; 25 times, you can see that there are no more free threads on the pool. At this point, the application “waits” for a free thread.&lt;br /&gt;&lt;li&gt;Once a thread is freed, the program grabs it right away, calling &lt;code&gt;Foo()&lt;/code&gt;, and still there are 0 free threads on the pool. This continues to happen until &lt;code&gt;Foo()&lt;/code&gt; is called 30 times. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;So right away, not doing anything too fancy, we can make a few comments about calling methods asynchronously.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Know that your code will run in a separate thread, so some thread safety issues may apply. This is a topic on its own, and I will not cover it here.&lt;br /&gt;&lt;li&gt;Remember that the pool has its limits. If you plan to call many functions asynchronously and if they take a long time to execute, Thread Pool Starvation might occur. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;BeginInvoke() and EndInvoke()&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;So far we saw how to invoke a method without really knowing when it is finished. But with &lt;code&gt;EndInvoke()&lt;/code&gt;, it is possible to do a few more things. First of all, &lt;code&gt;EndInvoke&lt;/code&gt; will block until your function completes execution; so, calling &lt;code&gt;BeginInvoke&lt;/code&gt; followed by &lt;code&gt;EndInvoke&lt;/code&gt; is really almost like calling the function in a blocking mode (because the &lt;code&gt;EndInvoke&lt;/code&gt; will wait until the function completes). But, how does the .NET runtime know how to bind a &lt;code&gt;BeginInvoke&lt;/code&gt; with an &lt;code&gt;EndInvoke&lt;/code&gt;? Well, that’s where &lt;code&gt;IAsyncResult&lt;/code&gt; comes in. When calling &lt;code&gt;BegineInvoke&lt;/code&gt;, the return object is an object of type &lt;code&gt;IAsyncResult&lt;/code&gt;; it is the glue that allows the framework to track your function execution. Think of it like a little tag to let you know what is going on with your function. With this little powerful super tag, you can find out when your function completes execution, and you can also use this tag to attach any state object you might want to pass to your function. Okay! Let’s see some examples so this doesn't become too confusing... Let's create a new &lt;code&gt;Foo&lt;/code&gt; function.&lt;/p&gt;&lt;pre lang="cs"&gt;private void FooOneSecond()&lt;br /&gt;{&lt;br /&gt;    // sleep for one second!&lt;br /&gt;    Thread.Sleep(1000);&lt;br /&gt;}&lt;/pre&gt;&lt;pre lang="cs"&gt;private void UsingEndInvoke()&lt;br /&gt;{&lt;br /&gt;    // create a delegate of MethodInvoker poiting to our Foo function.&lt;br /&gt;    MethodInvoker simpleDelegate = new MethodInvoker(FooOneSecond);&lt;br /&gt;&lt;br /&gt;    // start FooOneSecond, but pass it some data this time!&lt;br /&gt;    // look at the second parameter&lt;br /&gt;    IAsyncResult tag =&lt;br /&gt;        simpleDelegate.BeginInvoke(null, "passing some state");&lt;br /&gt;&lt;br /&gt;    // program will block until FooOneSecond is complete!&lt;br /&gt;    simpleDelegate.EndInvoke(tag);&lt;br /&gt;&lt;br /&gt;    // once EndInvoke is complete, get the state object&lt;br /&gt;    string strState = (string)tag.AsyncState;&lt;br /&gt;&lt;br /&gt;    // write the state object&lt;br /&gt;    Trace.WriteLine("State When Calling EndInvoke: "&lt;br /&gt;        + tag.AsyncState.ToString());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;What about Exceptions, how do I catch them?&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Now, let's make it a little more complicated. Let me modify the &lt;code&gt;FooOneSecond&lt;/code&gt; function and make it throw an exception. Now, you should be wondering how you will catch this exception. In the &lt;code&gt;BeginInvoke&lt;/code&gt;, or in the &lt;code&gt;EndInvoke&lt;/code&gt;? Or is it even possible to catch this exception? Well, it is not in the &lt;code&gt;BeginInvoke&lt;/code&gt;. The job of &lt;code&gt;BeginInvoke&lt;/code&gt; is to simply start the function on the &lt;code&gt;ThreadPool&lt;/code&gt;. It is really the job of the &lt;code&gt;EndInvoke&lt;/code&gt; to report all the information about the completion of the function, and this includes exceptions. Notice the next snippet of code:&lt;/p&gt;&lt;pre lang="cs"&gt;private void FooOneSecond()&lt;br /&gt;{&lt;br /&gt;    // sleep for one second!&lt;br /&gt;    Thread.Sleep(1000);&lt;br /&gt;    // throw an exception&lt;br /&gt;    throw new Exception("Exception from FooOneSecond");&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now, let's call &lt;code&gt;FooOneSecond&lt;/code&gt; and see if we can catch the exception.&lt;/p&gt;&lt;pre lang="cs"&gt;private void UsingEndInvoke()&lt;br /&gt;{&lt;br /&gt;    // create a delegate of MethodInvoker poiting&lt;br /&gt;    // to our Foo function.&lt;br /&gt;    MethodInvoker simpleDelegate =&lt;br /&gt;        new MethodInvoker(FooOneSecond);&lt;br /&gt;&lt;br /&gt;    // start FooOneSecond, but pass it some data this time!&lt;br /&gt;    // look at the second parameter&lt;br /&gt;    IAsyncResult tag = simpleDelegate.BeginInvoke(null, "passing some state");&lt;br /&gt;&lt;br /&gt;    try&lt;br /&gt;    {&lt;br /&gt;        // program will block until FooOneSecond is complete!&lt;br /&gt;        simpleDelegate.EndInvoke(tag);&lt;br /&gt;    }&lt;br /&gt;    catch (Exception e)&lt;br /&gt;    {&lt;br /&gt;        // it is here we can catch the exception&lt;br /&gt;        Trace.WriteLine(e.Message);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // once EndInvoke is complete, get the state object&lt;br /&gt;    string strState = (string)tag.AsyncState;&lt;br /&gt;&lt;br /&gt;    // write the state object&lt;br /&gt;    Trace.WriteLine("State When Calling EndInvoke: "&lt;br /&gt;        + tag.AsyncState.ToString());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;By running the code, you will see that the exception is only thrown and caught when calling &lt;code&gt;EndInvoke&lt;/code&gt;. If you decide to never call &lt;code&gt;EndInvoke&lt;/code&gt;, then you will not get the exception. However, when running this code within the debugger, depending on your exception settings, your debugger might stop when throwing the exception. But that is the debugger. Using a release version, if you don’t call &lt;code&gt;EndInvoke&lt;/code&gt;, you will never get the exception.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Passing parameters to your method&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Okay, so calling functions without parameters is not going to take us very far, so I am going to modify my super fancy and sophisticated &lt;code&gt;Foo&lt;/code&gt; function to take a few parameters.&lt;/p&gt;&lt;pre lang="cs"&gt;private string FooWithParameters(string param1,&lt;br /&gt;               int param2, ArrayList list)&lt;br /&gt;{&lt;br /&gt;    // lets modify the data!&lt;br /&gt;    param1 = "Modify Value for param1";&lt;br /&gt;    param2 = 200;&lt;br /&gt;    list = new ArrayList();&lt;br /&gt;&lt;br /&gt;    return "Thank you for reading this article";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let's call &lt;code&gt;FooWithParameters&lt;/code&gt; using &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt;. First of all, before we do anything, we must have a delegate that matches the signature of this method.&lt;/p&gt;&lt;pre lang="cs"&gt;public delegate string DelegateWithParameters(string param1,&lt;br /&gt;                       int param2, ArrayList list);&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Think of &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt; as cutting our function into two separate methods. The &lt;code&gt;BeginInvoke&lt;/code&gt; is responsible for accepting all the input parameters followed by two additional parameters every &lt;code&gt;BeginInvoke&lt;/code&gt; has (callback delegate, and a state object). The &lt;code&gt;EndInvoke&lt;/code&gt; is responsible for returning all output parameters (parameters marked with &lt;code lang="cs"&gt;ref&lt;/code&gt; or &lt;code lang="cs"&gt;out&lt;/code&gt;) and a return value, if there is one. Let's go back into our example to find out what are considered input parameters and what are output parameters. &lt;code&gt;param1&lt;/code&gt;, &lt;code&gt;param2&lt;/code&gt;, and &lt;code&gt;list&lt;/code&gt; are all considered input parameters, and therefore, they will be accepted as arguments to the &lt;code&gt;BeginInvoke&lt;/code&gt; method. The return value of type &lt;code lang="cs"&gt;string&lt;/code&gt; is considered an output parameter, and therefore, it will be the return type for &lt;code&gt;EndInvoke&lt;/code&gt;. The cool thing is that the compiler is able to generate the correct signature for &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt; based on the declaration of your delegate. Notice that I decided to modify the values of my input parameters just to examine if the behaviour is as I expect it to be without calling &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt;. I also re-allocate the &lt;code&gt;ArrayList&lt;/code&gt; that is passed to a new &lt;code&gt;ArrayList&lt;/code&gt;. So, try to guess what the output is going to be...&lt;/p&gt;&lt;pre lang="cs"&gt;private void CallFooWithParameters()&lt;br /&gt;{&lt;br /&gt;    // create the paramets to pass to the function&lt;br /&gt;    string strParam1 = "Param1";&lt;br /&gt;    int intValue = 100;&lt;br /&gt;    ArrayList list = new ArrayList();&lt;br /&gt;    list.Add("Item1");&lt;br /&gt;&lt;br /&gt;    // create the delegate&lt;br /&gt;    DelegateWithParameters delFoo =&lt;br /&gt;        new DelegateWithParameters(FooWithParameters);&lt;br /&gt;&lt;br /&gt;    // call the BeginInvoke function!&lt;br /&gt;    IAsyncResult tag =&lt;br /&gt;        delFoo.BeginInvoke(strParam1, intValue, list, null, null);&lt;br /&gt;&lt;br /&gt;    // normally control is returned right away,&lt;br /&gt;    // so you can do other work here...&lt;br /&gt;&lt;br /&gt;    // calling end invoke to get the return value&lt;br /&gt;    string strResult = delFoo.EndInvoke(tag);&lt;br /&gt;&lt;br /&gt;    // write down the parameters:&lt;br /&gt;    Trace.WriteLine("param1: " + strParam1);&lt;br /&gt;    Trace.WriteLine("param2: " + intValue);&lt;br /&gt;    Trace.WriteLine("ArrayList count: " + list.Count);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let's see our &lt;code&gt;FooWithParameters&lt;/code&gt; again, just so you don't need to scroll up.&lt;/p&gt;&lt;pre lang="cs"&gt;private string FooWithParameters(string param1,&lt;br /&gt;        int param2, ArrayList list)&lt;br /&gt;{&lt;br /&gt;    // lets modify the data!&lt;br /&gt;    param1 = "Modify Value for param1";&lt;br /&gt;    param2 = 200;&lt;br /&gt;    list = new ArrayList();&lt;br /&gt;&lt;br /&gt;    return "Thank you for reading this article";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let me give you the three lines from the output window after calling &lt;code&gt;EndInvoke()&lt;/code&gt;:&lt;/p&gt;&lt;pre lang="text"&gt;param1: Param1&lt;br /&gt;param2: 100&lt;br /&gt;ArrayList count: 1&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Okay, let’s analyze all this. Even when my function modifies the values of the input parameters, we don’t get to see those changes after calling &lt;code&gt;EndInvoke&lt;/code&gt;. The string is a mutable type, therefore, a copy of the string is created, and the change is not passed back to the caller. Integers are value types, and they create a copy when passed by value. Finally, re-creating the &lt;code&gt;ArrayList&lt;/code&gt; is not returned to the caller because the reference to the &lt;code&gt;ArrayList&lt;/code&gt; is passed by value, and in fact, re-creating the &lt;code&gt;ArrayList&lt;/code&gt; is simply creating a new allocation for &lt;code&gt;ArrayList&lt;/code&gt; assigning the "copied" reference that was passed. In fact, that reference is lost, and normally considered as a memory leak; but luckily for us, the .NET garbage collector will eventually grab it. So, what if we wanted to get back our new allocated &lt;code&gt;ArrayList&lt;/code&gt; and the rest of the changes we did to our parameters? What do we need to do? Well, it is simple; we simply have to tag the &lt;code&gt;ArrayList&lt;/code&gt; as a &lt;code lang="cs"&gt;ref&lt;/code&gt; parameter. Just for fun, let’s also add output parameters just to show how &lt;code&gt;EndInvoke&lt;/code&gt; is changed.&lt;/p&gt;&lt;pre lang="cs"&gt;private string FooWithOutAndRefParameters(string param1,&lt;br /&gt;        out int param2, ref ArrayList list)&lt;br /&gt;{&lt;br /&gt;    // lets modify the data!&lt;br /&gt;    param1 = "Modify Value for param1";&lt;br /&gt;    param2 = 200;&lt;br /&gt;    list = new ArrayList();&lt;br /&gt;&lt;br /&gt;    return "Thank you for reading this article";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let us see what is considered an output parameter and what is considered an input parameter…&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;code&gt;Param1&lt;/code&gt; is an input parameter, it will only be accepted within &lt;code&gt;BeginInvoke&lt;/code&gt;.&lt;br /&gt;&lt;li&gt;&lt;code&gt;Param2&lt;/code&gt; is input and output; therefore, it will be passed to both &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt; (&lt;code&gt;EndInvoke&lt;/code&gt; will give us the updated value).&lt;br /&gt;&lt;li&gt;&lt;code&gt;list&lt;/code&gt; is passed by reference, and therefore, it is too going to be passed to both &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt;. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Let’s see how our delegate looks like now:&lt;/p&gt;&lt;pre lang="cs"&gt;public delegate string DelegateWithOutAndRefParameters(string param1,&lt;br /&gt;                out int param2, ref ArrayList list);&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;and finally, let's look at the function that calls &lt;code&gt;FooWithOutAndRefParameters&lt;/code&gt;:&lt;/p&gt;&lt;pre lang="cs"&gt;private void CallFooWithOutAndRefParameters()&lt;br /&gt;{&lt;br /&gt;    // create the paramets to pass to the function&lt;br /&gt;    string strParam1 = "Param1";&lt;br /&gt;    int intValue = 100;&lt;br /&gt;    ArrayList list = new ArrayList();&lt;br /&gt;    list.Add("Item1");&lt;br /&gt;&lt;br /&gt;    // create the delegate&lt;br /&gt;    DelegateWithOutAndRefParameters delFoo =&lt;br /&gt;      new DelegateWithOutAndRefParameters(FooWithOutAndRefParameters);&lt;br /&gt;&lt;br /&gt;    // call the beginInvoke function!&lt;br /&gt;    IAsyncResult tag =&lt;br /&gt;        delFoo.BeginInvoke(strParam1,&lt;br /&gt;            out intValue,&lt;br /&gt;            ref list,&lt;br /&gt;            null, null);&lt;br /&gt;&lt;br /&gt;    // normally control is returned right away,&lt;br /&gt;    // so you can do other work here...&lt;br /&gt;&lt;br /&gt;    // calling end invoke notice that intValue and list are passed&lt;br /&gt;    // as arguments because they might be updated within the function.&lt;br /&gt;    string strResult =&lt;br /&gt;        delFoo.EndInvoke(out intValue, ref list, tag);&lt;br /&gt;&lt;br /&gt;    // write down the parameters:&lt;br /&gt;    Trace.WriteLine("param1: " + strParam1);&lt;br /&gt;    Trace.WriteLine("param2: " + intValue);&lt;br /&gt;    Trace.WriteLine("ArrayList count: " + list.Count);&lt;br /&gt;    Trace.WriteLine("return value: " + strResult);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Here is the output:&lt;/p&gt;&lt;pre lang="text"&gt;param1: Param1&lt;br /&gt;param2: 200&lt;br /&gt;ArrayList count: 0&lt;br /&gt;return value: Thank you for reading this article&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice that &lt;code&gt;param1&lt;/code&gt; does not change. It is an input parameter, and &lt;code&gt;param2&lt;/code&gt; was passed as an output parameter and was updated to 200. The array list has been reallocated, and now we see that it is pointing to a new reference of zero elements (the original reference is lost). I hope that now you understand how parameters are passed with &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt;. Let’s move on to looking at how to be notified if a non-blocking function is completed.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;What they don’t want you to know about IAsyncResult&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;You should be wondering how &lt;code&gt;EndInvoke&lt;/code&gt; is able to give us the output parameters and the updated &lt;code lang="cs"&gt;ref&lt;/code&gt; parameters. Or, better yet, how &lt;code&gt;EndInvoke&lt;/code&gt; is able to throw that exception we threw in our function. For example, say we called &lt;code&gt;BegineInvoke&lt;/code&gt; on &lt;code&gt;Foo&lt;/code&gt;, and then Foo finished executing, and now, we normally would call &lt;code&gt;EndInvoke&lt;/code&gt;, but what if we decide to call &lt;code&gt;EndInvoke&lt;/code&gt; 20 minutes after &lt;code&gt;Foo&lt;/code&gt; is finished? Notice that &lt;code&gt;EndInvoke&lt;/code&gt; will still give you those output or &lt;code lang="cs"&gt;ref&lt;/code&gt; parameters, and it would still throw that exception (if one was thrown). So, where is all that information stored? How come &lt;code&gt;EndInvoke&lt;/code&gt; is able to get all that data long after the function is completed? Well… the key is with the &lt;code&gt;IAsyncResult&lt;/code&gt; object! I decided to explore this object a little more, and as I suspected, it is this object that keeps all the information regarding your function call. Notice that &lt;code&gt;EndInvoke&lt;/code&gt; takes one parameter, it is an object of type &lt;code&gt;IAsyncResult&lt;/code&gt;. This object contains information such as:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Is the function completed?&lt;br /&gt;&lt;li&gt;A reference to the delegate used for &lt;code&gt;BeginInvoke&lt;/code&gt;&lt;br /&gt;&lt;li&gt;All output parameters and their values&lt;br /&gt;&lt;li&gt;All &lt;code lang="cs"&gt;ref&lt;/code&gt; parameters and their updated values&lt;br /&gt;&lt;li&gt;Return value&lt;br /&gt;&lt;li&gt;An Exception if one was thrown&lt;br /&gt;&lt;li&gt;And more… &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;code&gt;IAsyncResult&lt;/code&gt; may seem very innocent, because it is just an interface to a few little properties, but in fact, it is an object of type &lt;code&gt;System.Runtime.Remoting.Messaging.AsyncResult&lt;/code&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;img height="259" alt="AsyncResult" src="http://www.codeproject.com/csharp/AsyncMethodInvocation/Debug1.jpg" width="600" border="0" /&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now, if we dig a little deeper, we will find that &lt;code&gt;AsyncResult&lt;/code&gt; contains an object called &lt;code&gt;_replyMsg&lt;/code&gt; of type &lt;code&gt;System.Runtime.Remoting.Messaging.ReturnMessage&lt;/code&gt;, and what do you know… the holy grail has been found!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a title="Click to enlarge" href="http://www.codeproject.com/csharp/AsyncMethodInvocation/debug2.jpg" target="_blank"&gt;&lt;img height="377" alt="Check out the _replyMsg property... Its all there!" src="http://www.codeproject.com/csharp/AsyncMethodInvocation/debug2_small.jpg" width="600" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;i&gt;I had to shrink the above image so you won’t need to scroll to the right to read it, you can simply click on the image to view it&lt;/i&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;We can clearly see our return value, our output parameter, and our &lt;code lang="cs"&gt;ref&lt;/code&gt; parameters. There is even an exception property to hold the exception. Notice that I expanded, in the debug window for &lt;code&gt;OutArgs&lt;/code&gt; to show, the value 200 and a reference to the newly allocated &lt;code&gt;ArrayList&lt;/code&gt;. You can also see in the property &lt;code&gt;ReturnValue&lt;/code&gt;, the string “Thank you for reading this article”. If we had an exception, then the &lt;code&gt;EndInvoke&lt;/code&gt; would throw it for us to catch it. I think this is proof enough to conclude that all the information regarding your function call is saved with that little &lt;code&gt;IAsyncResult&lt;/code&gt; object you get back from &lt;code&gt;BeginInvoke&lt;/code&gt;, it is like a key to your data. If we lose this object, we will never know our output parameters, &lt;code lang="cs"&gt;ref&lt;/code&gt; parameters, and return value. It will also not be possible to catch an exception without this object. It’s the key! You lose it, and the info is lost forever in the maze of the .NET runtime… OK, getting a little carried away here. I think I made my point.&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Using the Callback delegate, Hollywood style "Don’t call me I will call you!"&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;At this point, you should understand how parameters can be passed, how to pass state, and understand the fact that your method is executed on a thread within the &lt;code&gt;ThreadPool&lt;/code&gt;. The only thing I didn’t really cover is the idea of being notified when the method is finished executing. After all, blocking and waiting for the method to finish does not accomplish much. In order to be notified when a method is complete, you must supply a callback delegate on the &lt;code&gt;BeginInvoke&lt;/code&gt;. OK, example! Look at the following two functions:&lt;/p&gt;&lt;pre lang="cs"&gt;private void CallFooWithOutAndRefParametersWithCallback()&lt;br /&gt;{&lt;br /&gt;    // create the paramets to pass to the function&lt;br /&gt;    string strParam1 = "Param1";&lt;br /&gt;    int intValue = 100;&lt;br /&gt;    ArrayList list = new ArrayList();&lt;br /&gt;    list.Add("Item1");&lt;br /&gt;&lt;br /&gt;    // create the delegate&lt;br /&gt;    DelegateWithOutAndRefParameters delFoo =&lt;br /&gt;        new DelegateWithOutAndRefParameters(FooWithOutAndRefParameters);&lt;br /&gt;&lt;br /&gt;    delFoo.BeginInvoke(strParam1,&lt;br /&gt;        out intValue,&lt;br /&gt;        ref list,&lt;br /&gt;        new AsyncCallback(CallBack), // callback delegate!&lt;br /&gt;        null);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void CallBack(IAsyncResult ar)&lt;br /&gt;{&lt;br /&gt;    // define the output parameter&lt;br /&gt;    int intOutputValue;&lt;br /&gt;    ArrayList list = null;&lt;br /&gt;&lt;br /&gt;    // first case IAsyncResult to an AsyncResult object, so we can get the&lt;br /&gt;    // delegate that was used to call the function.&lt;br /&gt;    AsyncResult result = (AsyncResult)ar;&lt;br /&gt;&lt;br /&gt;    // grab the delegate&lt;br /&gt;    DelegateWithOutAndRefParameters del =&lt;br /&gt;        (DelegateWithOutAndRefParameters) result.AsyncDelegate;&lt;br /&gt;&lt;br /&gt;    // now that we have the delegate,&lt;br /&gt;    // we must call EndInvoke on it, so we can get all&lt;br /&gt;    // the information about our method call.&lt;br /&gt;&lt;br /&gt;    string strReturnValue = del.EndInvoke(out intOutputValue,&lt;br /&gt;        ref list, ar);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;In here, you can see that we passed a delegate to the function &lt;code&gt;CallBack&lt;/code&gt; when calling &lt;code&gt;BeginInvoke&lt;/code&gt;. .NET will call us when the method &lt;code&gt;FooWithOutAndRefParameters&lt;/code&gt; completes execution. As before, we all know that we must call &lt;code&gt;EndInvoke&lt;/code&gt; if we want to get our output parameters. Notice that in order to call &lt;code&gt;EndInvoke&lt;/code&gt;, I needed to do some gymnastics to get the delegate.&lt;/p&gt;&lt;pre lang="cs"&gt;AsyncResult result = (AsyncResult)ar;&lt;br /&gt;// grab the delegate&lt;br /&gt;DelegateWithOutAndRefParameters del =&lt;br /&gt;    (DelegateWithOutAndRefParameters) result.AsyncDelegate;&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;Wait a minute! On which thread is the call-back executed on?&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;After all, the callback is invoked by .NET using your delegate, but still it is .NET that calls this delegate. It is your right and duty to know on which thread your code is executed on. To give a clear picture of what is going on, I decided to yet again modify my &lt;code&gt;Foo&lt;/code&gt; function to include thread information and add a delay of 4 seconds.&lt;/p&gt;&lt;pre lang="cs"&gt;private string FooWithOutAndRefParameters(string param1,&lt;br /&gt;        out int param2, ref ArrayList list)&lt;br /&gt;{&lt;br /&gt;    // log thread information&lt;br /&gt;    Trace.WriteLine("In FooWithOutAndRefParameters: Thread Pool? "&lt;br /&gt;        + Thread.CurrentThread.IsThreadPoolThread.ToString() +&lt;br /&gt;        " Thread Id: " + Thread.CurrentThread.GetHashCode());&lt;br /&gt;&lt;br /&gt;    // wait for 4 seconds as if this functions takes a while to run.&lt;br /&gt;    Thread.Sleep(4000);&lt;br /&gt;&lt;br /&gt;    // lets modify the data!&lt;br /&gt;    param1 = "Modify Value for param1";&lt;br /&gt;    param2 = 200;&lt;br /&gt;    list = new ArrayList();&lt;br /&gt;&lt;br /&gt;    return "Thank you for reading this article";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;I also added thread information to the callback function:&lt;/p&gt;&lt;pre lang="cs"&gt;private void CallBack(IAsyncResult ar)&lt;br /&gt;{&lt;br /&gt;    // which thread are we on?&lt;br /&gt;    Trace.WriteLine("In Callback: Thread Pool? "&lt;br /&gt;        + Thread.CurrentThread.IsThreadPoolThread.ToString() +&lt;br /&gt;        " Thread Id: " + Thread.CurrentThread.GetHashCode());&lt;br /&gt;&lt;br /&gt;    // define the output parameter&lt;br /&gt;    int intOutputValue;&lt;br /&gt;    ArrayList list = null;&lt;br /&gt;&lt;br /&gt;    // first case IAsyncResult to an AsyncResult object,&lt;br /&gt;    // so we can get the delegate that was used to call the function.&lt;br /&gt;    AsyncResult result = (AsyncResult)ar;&lt;br /&gt;&lt;br /&gt;    // grab the delegate&lt;br /&gt;    DelegateWithOutAndRefParameters del =&lt;br /&gt;        (DelegateWithOutAndRefParameters) result.AsyncDelegate;&lt;br /&gt;&lt;br /&gt;    // now that we have the delegate, we must call EndInvoke on it, so we&lt;br /&gt;    // can get all the information about our method call.&lt;br /&gt;    string strReturnValue = del.EndInvoke(out intOutputValue, ref list, ar);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;I decided to execute &lt;code&gt;FooWithOutAndRefParameters&lt;/code&gt; multiple times, using a button on my form.&lt;/p&gt;&lt;pre lang="cs"&gt;private void button4_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    CallFooWithOutAndRefParametersWithCallback();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Let’s see the output after pressing my button thrice (calling the function thrice):&lt;/p&gt;&lt;pre lang="text"&gt;In FooWithOutAndRefParameters: Thread Pool? True Thread Id: 7&lt;br /&gt;In FooWithOutAndRefParameters: Thread Pool? True Thread Id: 12&lt;br /&gt;In FooWithOutAndRefParameters: Thread Pool? True Thread Id: 13&lt;br /&gt;In Callback: Thread Pool? True Thread Id: 7&lt;br /&gt;In Callback: Thread Pool? True Thread Id: 12&lt;br /&gt;In Callback: Thread Pool? True Thread Id: 13&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice that my &lt;code&gt;Foo&lt;/code&gt; function is executed thrice, one after the other, on three separate threads. All the threads are on the thread pool. Notice also that the callback is also executed thrice, respectively, and they are all on the thread pool too. What makes this interesting is that, the callback seems to be executed on the same thread ID as &lt;code&gt;Foo&lt;/code&gt;. Thread 7 executes &lt;code&gt;Foo&lt;/code&gt;; 4 seconds later, the callback is also executed on thread 7. The same with thread 12 and 13. It is like the callback is a continuation of my &lt;code&gt;Foo&lt;/code&gt; function. I pressed my button many times, trying to see if the callback will ever be called on a thread Id other then the one &lt;code&gt;Foo&lt;/code&gt; is executed on, I was not able to achieve that. If you think about it, it makes total sense. Imagine, .NET would grab a thread to call &lt;code&gt;Foo&lt;/code&gt; and then grab another thread to call the callback, that would be a waste! Not to mention that if your thread pool is starved, you will end up waiting for a free thread just to call the callback! That would have been a disaster.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Using the Command Pattern to clean things up!&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Okay! Let's face it, things are getting a little messy. We have a &lt;code&gt;BeginInvoke&lt;/code&gt;, &lt;code&gt;EndInvoke&lt;/code&gt;, a callback, and they are all over the place! Let's try to use the Command Pattern to clean up the method invocation. Using the &lt;a href="http://www.dofactory.com/Patterns/PatternCommand.aspx" target="_blank"&gt;Command Pattern&lt;/a&gt; is simple and easy. Basically, you create a Command object that implements a simple interface like:&lt;/p&gt;&lt;pre lang="cs"&gt;public interface ICommand&lt;br /&gt;{&lt;br /&gt;    void Execute();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;It it time that we stop using our useless &lt;code&gt;Foo&lt;/code&gt; function everywhere, and try to do something more real! So, let's create a scenario that is more realistic. Say, we have the following:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;We have a user Form that contains a grid that displays customer rows.&lt;br /&gt;&lt;li&gt;The Grid is updated with rows based on a search criteria of customer ID. However, the database is far, far away, and it takes 5 seconds to get the customer dataset; we do not wish to block the UI while we are waiting.&lt;br /&gt;&lt;li&gt;We have a nice business object that is responsible to get our customer dataset based on a customer ID. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Suppose this was our Business Layer. To keep the example simple, I hard-coded what would normally come from a data layer.&lt;/p&gt;&lt;pre lang="cs"&gt;public class BoCustomer&lt;br /&gt;{&lt;br /&gt;    public DataSet GetCustomer(int intCustomerId)&lt;br /&gt;    {&lt;br /&gt;        // call data layer and get customer information&lt;br /&gt;        DataSet ds = new DataSet();&lt;br /&gt;        DataTable dt = new DataTable("Customer");&lt;br /&gt;        dt.Columns.Add("Id", typeof(int));&lt;br /&gt;        dt.Columns.Add("FirstName", typeof(string));&lt;br /&gt;        dt.Columns.Add("LastName", typeof(string));&lt;br /&gt;&lt;br /&gt;        dt.Rows.Add(intCustomerId, "Mike", "Peretz");&lt;br /&gt;        ds.Tables.Add(dt);&lt;br /&gt;&lt;br /&gt;        // lets make this take some time...&lt;br /&gt;        System.Threading.Thread.Sleep(2000);&lt;br /&gt;        return ds;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now, let's create our Command, which is responsible to update the grid based on the customer ID.&lt;/p&gt;&lt;pre lang="cs"&gt;public class GetCustomerByIdCommand : ICommand&lt;br /&gt;{&lt;br /&gt;    private GetCustomerByIdDelegate m_invokeMe;&lt;br /&gt;    private DataGridView m_grid;&lt;br /&gt;    private int m_intCustmerId;&lt;br /&gt;&lt;br /&gt;    // notice that the delegate is private,&lt;br /&gt;    // only the command can use it.&lt;br /&gt;    private delegate DataSet GetCustomerByIdDelegate(int intCustId);&lt;br /&gt;&lt;br /&gt;    public GetCustomerByIdCommand(BoCustomer boCustomer,&lt;br /&gt;        DataGridView grid,&lt;br /&gt;        int intCustId)&lt;br /&gt;    {&lt;br /&gt;        m_grid = grid;&lt;br /&gt;        m_intCustmerId = intCustId;&lt;br /&gt;&lt;br /&gt;        // setup the delegate to call&lt;br /&gt;        m_invokeMe =&lt;br /&gt;            new GetCustomerByIdDelegate(boCustomer.GetCustomer);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Execute()&lt;br /&gt;    {&lt;br /&gt;        // call the method on the thread pool&lt;br /&gt;        m_invokeMe.BeginInvoke(m_intCustmerId,&lt;br /&gt;            this.CallBack, // callback!&lt;br /&gt;            null);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void CallBack(IAsyncResult ar)&lt;br /&gt;    {&lt;br /&gt;        // get the dataset as output&lt;br /&gt;        DataSet ds = m_invokeMe.EndInvoke(ar);&lt;br /&gt;&lt;br /&gt;        // update the grid a thread safe fasion!&lt;br /&gt;        MethodInvoker updateGrid = delegate&lt;br /&gt;        {&lt;br /&gt;            m_grid.DataSource = ds.Tables[0];&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        if (m_grid.InvokeRequired)&lt;br /&gt;            m_grid.Invoke(updateGrid);&lt;br /&gt;        else&lt;br /&gt;            updateGrid();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice that the &lt;code&gt;GetCustomerByIdCommand&lt;/code&gt; takes all the information it needs to execute the command.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The grid to update.&lt;br /&gt;&lt;li&gt;The customer ID to search.&lt;br /&gt;&lt;li&gt;A reference to the business layer. &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Also notice that the delegate is hidden within the Command object, so the client doesn’t need to know the inner working of the Command. All the client needs to do is build the Command and call &lt;code&gt;Execute&lt;/code&gt; on it. We all know by now that asynchronous methods invocation is done on the &lt;code&gt;ThreadPool&lt;/code&gt;, and we should all know by now that it is not healthy to update the UI from the &lt;code&gt;ThreadPool&lt;/code&gt; or any other thread other then the UI thread! So, to fix this problem, we hide this implementation within the Command, and check based on the Grid if &lt;code&gt;InvokeRequired()&lt;/code&gt; is true. If it is true, we use &lt;code&gt;Control.Invoke&lt;/code&gt; to make sure the call is marshaled to the UI thread. (Notice, I am using the .NET 2.0 features of creating anonymous methods.) Let's see how the form is creating the command and executing it!&lt;/p&gt;&lt;pre lang="cs"&gt;private ICommand m_cmdGetCustById;&lt;br /&gt;private void button1_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    // get the custmer id from the screen&lt;br /&gt;    int intCustId = Convert.ToInt32(m_txtCustId.Text);&lt;br /&gt;&lt;br /&gt;    // use the buisness layer to get the data&lt;br /&gt;    BoCustomer bo = new BoCustomer();&lt;br /&gt;&lt;br /&gt;    // create a command that has all the tools to update the grid&lt;br /&gt;    m_cmdGetCustById = new GetCustomerByIdCommand(&lt;br /&gt;        bo, m_grid, intCustId);&lt;br /&gt;&lt;br /&gt;    // call the command in a non blocking mode.&lt;br /&gt;    m_cmdGetCustById.Execute();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice, that &lt;code&gt;Execute&lt;/code&gt; is non-blocking. But before you go nuts and create a million command classes, keep these in mind:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The Command Pattern may cause class explosion, so choose your weapon wisely.&lt;br /&gt;&lt;li&gt;In my case, it would have been easy to create a base class to my command that has the logic to update a grid in a thread-safe manner, but I kept my example simple.&lt;br /&gt;&lt;li&gt;It would also be acceptable to pass the &lt;code&gt;TextBox&lt;/code&gt; into the command object so it can grab the input in a more dynamic way and allow the command to be called anytime without re-creating it.&lt;br /&gt;&lt;li&gt;Notice that the delegate, &lt;code&gt;BeginInvoke&lt;/code&gt;, &lt;code&gt;EndInvoke&lt;/code&gt;, callback, and our crazy code to make sure the UI is updated in a thread safe manner is all encapsulated in my Command, which is a good thing! &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Phew! It took me almost a week to write this fun article. I tried to cover all the important aspects of calling a method in a non-blocking mode. Here are a few things to remember:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Delegates will contain the correct signature for &lt;code&gt;BeginInvoke&lt;/code&gt; and &lt;code&gt;EndInvoke&lt;/code&gt;, you should expect all output parameters and exceptions to come out when calling &lt;code&gt;EndInvoke&lt;/code&gt;.&lt;br /&gt;&lt;li&gt;Don’t forget you take juice from the &lt;code&gt;ThreadPool&lt;/code&gt; when using &lt;code&gt;BeginInvoke&lt;/code&gt;, so don’t overdue it!&lt;br /&gt;&lt;li&gt;If you plan to use a callback, it might be a good idea to use the Command Pattern to hide all the nasty code that goes with it.&lt;br /&gt;&lt;li&gt;Personally, the UI should only be blocked when doing UI stuff, so now you have no excuse! &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Thank you for reading, have a wonderful day, and happy .NET coding everyone!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9202309254227413537-386131875390359264?l=mikeperetz.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://mikeperetz.blogspot.com/feeds/386131875390359264/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9202309254227413537&amp;postID=386131875390359264' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/386131875390359264'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9202309254227413537/posts/default/386131875390359264'/><link rel='alternate' type='text/html' href='http://mikeperetz.blogspot.com/2007/11/int-x-100.html' title='Asynchronous Method Invocation'/><author><name>Mike Peretz</name><uri>http://www.blogger.com/profile/01090154270652506561</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>
