Words on my addictions: .NET, Philosophy, Music

22 March 2007

Stop threads gracefuly

Filed under: C# — stefanprodan @ 2:50 pm

Every time you are using threads in your code you’ll need a way to stop them and from what I have been experienced the Thread.Abort() is not a choice. Thread.Abort will allways throw ThreadAbortException and what is worse is that the throw is asynchronous so a simple try/catch will not be helpful. On the Abort method the MSDN tells us that “the thread is not guaranteed to abort immediately, or at all” and better yet “If two calls to Abort come at the same time, it is possible that one call set the state information and the other call executes the Abort. However, an application cannot distinguish this.”.

In order to stop a worker in a graceful way you’ll need to use a volatile member in the worker class. My implementation follows:

ReadyForThreading class:

public abstract class ReadyForThreading
{
private readonly object locker = new object();
private bool stopRequired = false;
private bool isStopped = false;

public bool IsStopped
{
get
{
lock (locker) { return isStopped; }
}
protected set
{
lock (locker) { isStopped = value; }
}
}

public bool IsStopping
{
get
{
lock (locker) { return stopRequired; }
}
}

public void Stop()
{
lock (locker) { this.stopRequired = true; }
}
}

Now all you need to do is design your worker class based on the ReadyForThreading:

Worker example class:

public class SomeWorker : ReadyForThreading
{
public void DoWork(object state)
{
try
{
int i = 0;
while (!base.IsStopping)
{
// do work
Thread.Sleep(2000);
Console.WriteLine(”Working on {0} part 1 loop {1}”,
state.ToString(), i);

if (base.IsStopping)
{
break;
}

//do more work
Thread.Sleep(3000);
Console.WriteLine(”Work part 2 loop ” + i);

i++;
}
}
finally
{
base.IsStopped = true;
}
}
}

Usage example:

SomeWorker worker = new SomeWorker();
Thread th = new Thread(new ParameterizedThreadStart(worker.DoWork));
th.Start(”SomeObject”);
Console.WriteLine(”Press any key to stop the worker”);
Console.ReadLine();
worker.Stop();

kick it on DotNetKicks.com

10 Comments »

  1. Hello.
    I ma first time here.
    Cute, a lot of useful info here.
    But i want to know where i can read more?
    Any directions?

    Comment by TieliqueBut — 3 September 2007 @ 2:27 am

  2. very interesting. i’m adding in RSS Reader

    Comment by Melina — 20 December 2007 @ 9:43 pm

  3. Hi :
    I’m from Argentina, happy to hear from cool folks here.
    Hasta la vista.

    Target Stores

    Comment by BibRobIonitty — 3 February 2008 @ 2:25 am

  4. Hi
    I am a new member here. I am from the US and am 25 years old. I am here to
    share my experiences and gain from your expertise.

    Comment by propertyarchives — 9 March 2008 @ 4:46 am

  5. Hello All
    Im New…

    Comment by megatrendsZ — 10 March 2008 @ 10:51 pm

  6. [size=72][color=red][url=http://www.goadult.info/go.php?sid=9]ВХОД НА ПОРНО САЙТ[/url][/color][/size]

    [size=46][color=red][url=http://www.goadult.info/go.php?sid=9]>>> ENTER <<>> ENTER <<<[/url][/color][/size]

    [size=72][color=red][url=http://www.goadult.info/go.php?sid=9]ВХОД НА ПОРНО САЙТ[/url][/color][/size]

    [size=72][b]порно фетиш фильм загрузить[/b][/size]

    [b]порно фильм скачать[/b]
    [b]видео порно загрузить [/b]
    [b]xxx ролик скачать [/b]
    [b]эротика видио загрузить [/b]

    [url=http://www.sex-traher.ru/]www порно фото[/url]
    [url=http://sex-traher.ru/lesbon]анал секс forum[/url]
    [url=http://sex-traher.ru/contests]подростки порно[/url]
    [url=http://sex-traher.ru/vkusnii-klitor]анал секс blogs[/url]
    [url=http://sex-traher.ru/house]порно группа фабрика[/url]
    [url=http://sex-traher.ru/fuckin]короткое порно видео[/url]
    [url=http://sex-traher.ru/hot-vagin]порно пизда comment[/url]
    [url=http://sex-traher.ru/moya]японское порно онлайн[/url]
    [url=http://sex-traher.ru/play]видео портал порно[/url]
    [url=http://sex-traher.ru/soirtir-cam]порно онлайн негры[/url]
    [url=http://sex-traher.ru/perfect]www бесплатное порно ru[/url]
    [url=http://sex-traher.ru/warnings]мужчина женщина[/url]
    [url=http://sex-traher.ru/spy-girls]мужчина женщина[/url]
    [url=http://sex-traher.ru/camera-sex]секс парней[/url]
    [url=http://sex-traher.ru/banged]бесплатное русское порно видео[/url]
    [url=http://sex-traher.ru/ass]порно line journal[/url]
    [url=http://sex-traher.ru/anusik]анастасия заворотнюк порно[/url]
    [url=http://sex-traher.ru/sladkii]line порно[/url]
    [url=http://sex-traher.ru/see]порно 18 скачать[/url]
    [url=http://sex-traher.ru/analchik]порно фото 2[/url]
    [url=http://sex-traher.ru/brunetka]гей видео[/url]
    [url=http://sex-traher.ru/masturbacia]порно толстые бабы[/url]
    [url=http://sex-traher.ru/world-wide-web]скрытая порно камера бесплатно[/url]
    [url=http://sex-traher.ru/lover]елена порно фото[/url]
    [url=http://sex-traher.ru/rolik]бесплатное порно девственницы[/url]
    [url=http://sex-traher.ru/perfect-sex]платные порно сайты[/url]
    [url=http://sex-traher.ru/girl]японское порно фото[/url]
    [url=http://sex-traher.ru/clappers]порно анал[/url]
    [url=http://sex-traher.ru/fucking]онанизм[/url]
    [url=http://sex-traher.ru/wc]часное порно[/url]
    [url=http://sex-traher.ru/hot-anal]www порно видео[/url]
    [url=http://sex-traher.ru/cocks]секс подростков[/url]
    [url=http://sex-traher.ru/my]порно сперма видео[/url]
    [url=http://sex-traher.ru/shkola]просмотр порно[/url]
    [url=http://sex-traher.ru/beauti-sex]жопу[/url]
    [url=http://sex-traher.ru/wc-cam]смотреть порно фильмы[/url]
    [url=http://sex-traher.ru/devochka]секс[/url]
    [url=http://sex-traher.ru/fuckorama]первый секс парню[/url]
    [url=http://sex-traher.ru/play-go]гей видео онлайн[/url]
    [url=http://sex-traher.ru/epopik]онлайн порно тв[/url]
    [url=http://sex-traher.ru/download]гей фильмы[/url]
    [url=http://sex-traher.ru/go]качать порно[/url]
    [url=http://sex-traher.ru/popa]зрелые женщины[/url]
    [url=http://sex-traher.ru/super-anal]молоденькие blogs[/url]
    [url=http://sex-traher.ru/popik]порно анастасии[/url]
    [url=http://sex-traher.ru/dom]www секс видео[/url]
    [url=http://sex-traher.ru/virgin-nice]скачать порно видео бесплатно[/url]
    [url=http://sex-traher.ru/anonirovanie]порнуха ролики blog[/url]
    [url=http://sex-traher.ru/girls]порно блондинка[/url]
    [url=http://sex-traher.ru/free]красивые голые девушки[/url]
    [url=http://sex-traher.ru/vaginator]порно видео просмотр[/url]
    [url=http://sex-traher.ru/zad]бесплатная онлайн порнуха[/url]
    [url=http://sex-traher.ru/you]просмотр порно бесплатно[/url]
    [url=http://sex-traher.ru/suber]без регистрации скачать порно видео[/url]

    порно скачать
    порнуха загрузить
    эротика видио посмотреть
    порно загрузить
    видео порно ролик посмотреть
    видео порно ролик загрузить
    порно ролик скачать

    Comment by fahfive — 16 April 2009 @ 8:33 am

  7. [b]That is why so uncountable fools on the Internet?[/b]

    Comment by grailmTealiag — 17 May 2009 @ 5:18 am

  8. гдето тут говрили в этот о
    что можно купить металлочерепицу в розницу в Москве ? да, и профнастил вроде тоже – мягкую кровлю делать ?

    Comment by Ambippili — 24 May 2009 @ 8:19 am

  9. I feel I might introduce my self here. My name is Kate, I’m a newbie here, someone told me that i might find some good information here so… basically that’s why I’m here, and for any good advice i might get also… hope to have good time here

    Comment by gretamandisson — 14 June 2009 @ 12:09 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.