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