Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - Start and stop(forced) a threaded job

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...