Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Declarative multithreading

, 13 Mar 2012
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)

Share

About the Author

gossd
Systems Engineer
Germany Germany
No Biography provided

| Advertise | Privacy | Mobile
Web02 | 2.8.140922.1 | Last Updated 13 Mar 2012
Article Copyright 2011 by gossd
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid