DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

"Extend" The Thread Class In Csharp

06.29.2007
| 6322 views |
  • submit to reddit
        //just inherit from the EasyThread class and override the PerformWork method

   public class EasyThread: IDisposable
    {
        Thread WorkerThread;
        public EasyThread()
        {
            if (WorkerThread == null)
                WorkerThread = new Thread(new ThreadStart(PerformWork));
        }


        public void Run()
        {
            if (WorkerThread.IsAlive == false)
                WorkerThread.Start();

            if (WorkerThread.ThreadState == ThreadState.Suspended)
                WorkerThread.Resume();
        }

        /// <summary>
        /// EasyThread provides a facade to inheriting from a Thread class.
        /// Override the perform work method to perform your tasks.
        /// </summary>
        protected virtual void PerformWork()
        {

        }

        public void Pause()
        {
            WorkerThread.Suspend();
        }

        public void Quit()
        {
            Cleanup();
        }

        private void Cleanup()
        {
            WorkerThread.Join(0);
            WorkerThread = null;
        }

        public void Dispose()
        {
            Cleanup();
        }
    }