Mi sono spesso trovato di fronte al conflitto tra la programmazione Object Oriented e la necessità di usare le caratteristiche multithreading del sistema operativo. Alla fine si tratta di scrivere una procedura, sotto forma di metodo, e pur esistendo delle classi che lo fanno, in se la cosa non si presta bene ad essere racchiusa in un'ottica object oriented. Qui sotto vi propongo una classe che usa il pattern Singleton per incapsulare un thread e tutto ciò che serve per controllarlo.

Io l'ho realizzata per racchiudere i vari thread che lavorano all'interno di un Windows Service che ho creato, e l'ho trovata molto comoda.

using System;
using System.Threading; 

public class WorkingThread
 {
    private static WorkingThread m_Instance;
    private AutoResetEvent m_ExitEvent;
    private Thread m_Thread;
    private bool m_Running;

    private WorkingThread()
    {
        m_ExitEvent = new AutoResetEvent( false );
        m_Running = false;
    }

    public static WorkingThread Instance
    {
        get
        {
            if ( m_Instance == null )
                m_Instance = new WorkingThread();

            return m_Instance;
        }
    }

    public bool IsRunning
    {
        get { return m_Running; }
    }

    public void Start()
    {
        if ( !IsRunning )
        {
            m_ExitEvent.Reset();

            ThreadStart startInfo = new ThreadStart( Thread_Proc );
            m_Thread = new Thread( startInfo );
            m_Thread.Start();

            m_Running = true;
        }
        else
            throw new InvalidOperationException( "Thread already running" );
    }

    public void Stop()
    {
        if ( IsRunning )
        {
            m_ExitEvent.Set();
            m_Running = false;
        }
       
else
            throw new
InvalidOperationException( "Thread already stopped" );
    }

    protected void Thread_Proc()
    {
        WaitHandle [] handles = new WaitHandle [] { m_ExitEvent };

        while( WaitHandle.WaitAny( handles, 1000, false ) == WaitHandle.WaitTimeout )
        {
       
     // do something
            Thread.Sleep( 1000 );
        }
    }
}

L'uso è banale. La classe ha una proprietà Instance che rappresenta il thread che deve essere lanciato e ha i metodi Start() e Stop() per avviarlo e fermarlo.

public void Main()
{
    WorkerThread.Instance.Start();
    //
    WorkerThread.Instance.Stop();
}

Ancora una volta l'applicazione dei design pattern dimostra la sua potenza.

N.B. Approfondite i commenti a questo post, perchè c'è molto da imparare.