Click here to Skip to main content
11,929,950 members (36,039 online)
Click here to Skip to main content


134 bookmarked

Declarative multithreading

, 13 Mar 2012 CDDL
An introduction and proof of concept code for the idea of declarative multi threading in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadBound
    /// <summary>
    /// Implements the extension Method for the class Object that allows binding iterfaces to threads.
    /// </summary>
    public static class ThreadBoundInterface
        /// <summary>
        /// Creates an interface where all method calls are executed within the current thread.
        /// </summary>
        /// <typeparam name="T">Type of the interface that should be bound to this thread.</typeparam>
        /// <param name="realObject">Reference to the real object instance. The referenced object must implement T.</param>
        /// <returns>Returns an instance of a proxy class implementing interface T.</returns>
        /// <example><code>
        ///     IUpdateInterface threadBoundUpdater = this.BindInterfaceToThread<IUpdateInterface>();
        /// </code></example>
        static public T BindInterfaceToThread<T>(this Object realObject) where T : class 
            SynchronizationContext executionContext = SynchronizationContext.Current;

            //-- To bind an interface to a thread a proxy must be generated on the fly. This proxy
            //   forwards all calls to the real instance but is derived from ContextBoundObject.
            //   This is very time consuming and should only be used if neccessary. But it's working pretty well.
            MarshalByRefObject wrapper = InterfaceProxyGenerator.CreateProxy((T)realObject);

            //-- Create a proxy from the existing object and return an instance of the transparent proxy hat
            //   was created for the proxy class. (TransparentProxy -> RealProxy -> InterfaceProxy -> Interface)
            ThreadBoundProxy newProxy = new ThreadBoundProxy(typeof(T), (MarshalByRefObject)wrapper, executionContext);
            return (T)newProxy.GetTransparentProxy();

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

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


This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


About the Author

Systems Engineer
Germany Germany
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 13 Mar 2012
Article Copyright 2011 by gossd
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid