Click here to Skip to main content
12,948,130 members (67,619 online)
Click here to Skip to main content


137 bookmarked
Posted 22 Nov 2011

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 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>
    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.
        public void CreateNumbers(int limit, int delay)
            CancelFlag = false;
            for (int i = 0; i <= limit; i++)
                if (NewNumber!=null)

                if (CancelFlag)
        //-- 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.
        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.


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...

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