简体   繁体   中英

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);
}

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM