BossRoss
BossRoss

Reputation: 869

Stopping a Specific Thread and Starting It Up Again From Windows Service

I want to know how to stop and restart a thread.

I create N amount of threads, depending on conditions returned from a database. These are long running processes which should never stop but should I get a critical error within the thread I want to completely kill the thread and start it up like new.

The code which I use currently to start the threads:

foreach (MobileAccounts MobileAccount in ReceiverAccounts)
{
    Receiver rec = new Receiver();
    ThreadStart starterParameters = delegate { rec.StartListener(MobileAccount); };
    Thread FeedbackThread = new Thread(starterParameters);
    FeedbackThread.Name = MobileAccount.FriendlyName;

    FeedbackThread.Start();
    Thread.Sleep(1000);
}

Upvotes: 0

Views: 65

Answers (1)

mehmet mecek
mehmet mecek

Reputation: 2685

You can write your own listener and manage its thread within it.

something like:

public class AccountListener
{
    private Thread _worker = null;
    private MobileAccount _mobileAccount;
    public AccountListener(MobileAccount mobileAccount)
    {
        _mobileAccount = mobileAccount;
    }

    protected void Listen()
    {
        try
        {
            DoWork();
        }
        catch (Exception exc)
        {
        }
    }

    protected virtual void DoWork()
    {
        Console.WriteLine(_mobileAccount);
    }

    public void Start()
    {
        if (_worker == null)
        {
            _worker = new Thread(Listen);
        }
        _worker.Start();
    }

    public void Stop()
    {
        try
        {
            _worker.Abort();
        }
        catch (Exception)
        {
            //thrad abort exception
        }
        finally
        {
            _worker = null;
        }
    }
}

Upvotes: 1

Related Questions