[C#] ThreadRunner Example

Discussion in 'C#' started by BinaryX, Apr 19, 2013.

  1. BinaryX

    BinaryX Lifetime Gold XPG Developer Lifetime Gold
    205/282

    971
    258
    0
    May 21, 2011
    Europe
    Console:
    Xbox
    Hi XPG!

    Something i wrote out of boredom, basically uses threads in combination with OOP.
    You can spawn new worker threads with a select interval and also suspend them again.
    Console output is also redirected to a RIchTextBox.

    Source is for download below, you'll have to compile the binary yourself!
    Download Source

    Enjoy :)
     
  2. CRACKbomber

    CRACKbomber Resident Xbox Guru XPG Developer
    25/47

    276
    235
    25
    Sep 12, 2011
    Michigan
    Console:
    Xbox
    A couple things to add to this.
    You should have your thread class expand the IDisposable interface instead of just implementing a dispose function.

    public class Worker : IDisposable
    {
    private Thread t;
    private frmMain parent;
    public int interval, cycle = 1;
    private volatile bool _ShouldStop;
    private bool disposed = false;
    public Worker(frmMain parent, int interval = 1000)
    {
    this.parent = parent;
    this.interval = interval;
    this.t = new Thread(new ThreadStart(this.loop));
    t.Start();
    }

    public void loop()
    {
    parent.logger.Write("Thread " + getID() + " executing.");
    while (!_ShouldStop)
    {
    Thread.Sleep(this.interval);
    parent.logger.Write("Thread" + getID() + " - cycle " + this.cycle + ".");
    cycle++;
    }
    }

    protected virtual void Dispose(bool disposing)
    {
    if (!disposed)
    {
    if (disposing)
    {
    ///Terminates thread
    t.Join();
    }

    disposed = true;
    }
    }

    public void Dispose()
    {
    Dispose(true);
    GC.SuppressFinalize(this);
    }

    public int getID()
    {
    return t.ManagedThreadId;
    }
    }


    So with this you can use the using keyword to automatically dispose of threads once you are done with them.

    Anyways, good job with the program!
     
  3. BinaryX

    BinaryX Lifetime Gold XPG Developer Lifetime Gold
    0/47

    971
    258
    0
    May 21, 2011
    Europe
    Console:
    Xbox
    Thanks man +rep, i still got lots of things to learn.
     
  4. Warmonger

    Warmonger Newbie BANNED
    0/47

    26
    1
    0
    Jun 19, 2012
    Console:
    Other
    Update your source link. I'm eager to run through the mistakes it may have.
     
  5. Admin Post
    Iamcoolz

    Iamcoolz Forum Administrator Staff Member XPG Administrator
    205/282

    1,227
    507
    205
    Mar 30, 2012
    XPG
    Console:
    Xbox One
    So sure of himself.

    Wonderful job my man, it will come to you. Thanks for the contribution! Repped.
     

Share This Page