[C#] ThreadRunner Example

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

  1. BinaryX

    BinaryX Lifetime Gold XPG Developer Lifetime Gold
    205/282

    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

    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

    Thanks man +rep, i still got lots of things to learn.
     
  4. Warmonger

    Warmonger Newbie BANNED
    0/47

    Update your source link. I'm eager to run through the mistakes it may have.
     
  5. Iamcoolz

    Iamcoolz Forum Administrator Staff Member XPG Administrator
    205/282

    So sure of himself.

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

Share This Page