Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to know a proper way to start and stop a threaded job forced and unforced. Is this the proper way to stop a Thread?

    public class ProcessDataJob : IJob
    {
        private ConcurrentQueue<byte[]> _dataQueue = new ConcurrentQueue<byte[]>();
        private volatile bool _stop = false;
        private volatile bool _forceStop = false;
        private Thread _thread;
        private int _timeOut = 1000;

        public void Start()
        {
            _stop = false;
            _forceStop = false;

            _thread = new Thread(ProcessData);
            _thread.Start();
        }

        private void ProcessData()
        {
            while (!_stop || _dataQueue.Count > 0)
            {
                if(_forceStop) return;

                byte[] data;
                if(_dataQueue.TryDequeue(data))
                {
                   //Process data
                   //.....//
                }
            }
        }

        public void Stop(bool force)
        {
            _stop = true;
            _forceStop = force;
            _thread.Join(_timeOut); 
        }

        public void Enqueue(byte[] data)
        {
            _dataQueue.Enqueue(data);
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is no proper way to forcibly kill a thread.

There are several ways to do it, but none of them are proper.

Forcibly killing a thread is what you should do only if you need to terminate the program, or unload the appdomain containing the thread, and don′t care about any data structures left dangling in a corrupted/bad/locked state, because they will be gone in a short while as well.

There′s plenty of advice on the internet about how bad/evil Thread.Abort is, so don′t do it.

Instead, write proper cooperative threading. The thread(s) should themselves check a flag (event, volatile bool field, etc.) and then voluntairly exit when nicely asked to do so.

That is the proper way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...