Click here to Skip to main content
15,896,154 members
Articles / General Programming / Threads

Declarative multithreading

Rate me:
Please Sign up or sign in to vote.
4.94/5 (39 votes)
13 Mar 2012CDDL19 min read 59.2K   862   139  
An introduction and proof of concept code for the idea of declarative multi threading in C#.
using System;
using ThreadBound;
using System.Threading;

namespace FormsTest
{
    /// <summary>
    /// This is the Worker-Class. It is very lightweight because the whole threading
    /// overhead is just a bunch of attributes.
    /// Event the event does not need much special attention.
    /// </summary>
    [ThreadBound(ThreadBoundAttribute.ThreadBinding.PoolContext)]
    class NumberWorker : ThreadBoundObject, IDisposable
    {
        //-- This is the cancel-flag. It must be declared volatile because it's
        //   used from an other thread.
        private volatile bool CancelFlag=false;

        //-- This is the NewNumber-event. It is called from the worker-thread as soon
        //   as a new number is available.
        public delegate void NewNumberHandler(int number);
        public event NewNumberHandler NewNumber;

        //-- This is the worker method. It creates a new number from 0 to limit every second.
        //   Because this method is marked as AsyncThreaded and it will be executed in a background
        //   thread and the method call will return immediately.
        [AsyncThreaded]
        public void CreateNumbers(int limit, int delay)
        {
            CancelFlag = false;
            for (int i = 0; i <= limit; i++)
            {
                Thread.Sleep(delay);
                if (NewNumber!=null)
                    NewNumber(i);

                if (CancelFlag)
                    break;
            }
        }
        
        //-- The FreeThreaded-attribute of this method allows it to be called from any thread.
        //   It does not have to wait for the other methods to finish and can set the cancel-
        //   flag at any time.
        [FreeThreaded]
        public void Cancel()
        {
            CancelFlag = true;
        }

        public void Dispose()
        {
        }
    }
}

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

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

License

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


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

Comments and Discussions