Click here to Skip to main content
15,897,187 members
Articles / Desktop Programming / WPF

Beginner's Guide to Threading in .NET: Part 2 of n

Rate me:
Please Sign up or sign in to vote.
4.91/5 (267 votes)
10 Aug 2008CPOL23 min read 453.2K   2.6K   448  
A beginner's guide to threading in .NET.
using System;
using System.ComponentModel;
using System.Threading;

namespace ThreadResumePause_StopUsingEventArgs
{

    public delegate void ReportWorkDoneEventhandler(object sender, 
    WorkDoneCancelEventArgs e);
    
    /// <summary>
    /// This class provides a background worker that finds prime numbers, that
    /// are reported to the UI via the ReportWorkDone event. The UI may pause
    /// the worker by calling the Pause() method, and may resume the worker by
    /// calling the Resume() method. The UI may also cancel the worker by setting
    /// the ReportWorkDone events event args Cancel property to true.
    /// </summary>
    public class WorkerThread
    {

        private Thread worker;
        public event ReportWorkDoneEventhandler ReportWorkDone;
        private volatile bool cancel = false;
        private ManualResetEvent trigger = new ManualResetEvent(true);

        //ctor
        public WorkerThread()
        {
            
        }


        //Do the work, start the thread
        public void Start(long primeNumberLoopToFind)
        {
            worker = new Thread(new ParameterizedThreadStart(DoWork));
            worker.Start(primeNumberLoopToFind);
        }


        //Thread start method
        private void DoWork(object data)
        {

            long primeNumberLoopToFind = (long)data;

            int divisorsFound = 0;
            int startDivisor = 1;

            
            for (int i = 0; i < primeNumberLoopToFind; i++)
            {
                //wait for trigger
                trigger.WaitOne();

                divisorsFound = 0;
                startDivisor = 1;

                //check for prime numbers, and if we find one raise
                //the ReportWorkDone event
                while (startDivisor <= i)
                {
                    if (i % startDivisor == 0)
                        divisorsFound++;
                    startDivisor++;
                }
   
                if (divisorsFound == 2)
                {

                    WorkDoneCancelEventArgs e = 
                        new WorkDoneCancelEventArgs(i);
                    OnReportWorkDone(e);
                    cancel = e.Cancel;

                    //check whether thread should carry on, 
                    //perhaps user cancelled it
                    if (cancel)
                        return;
                }
            }
        }


        /// <summary>
        /// make the worker thread wait on the ManualResetEvent
        /// </summary>
        public void Pause()
        {
            trigger.Reset();
        }


        /// <summary>
        /// signal the worker thread, raise signal on 
        /// the ManualResetEvent
        /// </summary>
        public void Resume()
        {
            trigger.Set();
        }


        /// <summary>
        /// Raise the ReportWorkDone event
        /// </summary>
        protected virtual void OnReportWorkDone(WorkDoneCancelEventArgs e) 
        {
            if (ReportWorkDone != null) 
            {
                ReportWorkDone(this, e); 
            }
        }
    }



    //Simple cancellable EventArgs, that also exposes 
    //current prime number found to UI
    public class WorkDoneCancelEventArgs : CancelEventArgs 
    {
        public int PrimeFound { get; private set; }

        public WorkDoneCancelEventArgs(int primeFound)
        {
            this.PrimeFound = primeFound;
        }
    }


}

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 Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions