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


i want know proper way start , stop threaded job forced , unforced. proper way stop 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);         }     } 

there no proper way forcibly kill thread.

there several ways it, none of them proper.

forcibly killing thread should if need terminate program, or unload appdomain containing thread, , don´t care data structures left dangling in corrupted/bad/locked state, because gone in short while well.

there´s plenty of advice on internet how bad/evil thread.abort is, don´t it.

instead, write proper cooperative threading. thread(s) should check flag (event, volatile bool field, etc.) , voluntairly exit when nicely asked so.

that proper way.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -