Techno
Oct 19th, 2007, 04:20 AM
I am wanting to re-use a thread I have created, to do some work.
What is the best way of doing this? I don't want to spin up a new thread each time this "DoWork()" Method is called. I'd rather have the same thread run the same task. It will only be called when a task has finished completing.
Whats happening is this:
My business logic spins up a thread to run a method.
This method is kind of using a for loop, but not quite - basically checking the index stored globally to see if its < than a collection of items. If so, it will do some work.
There will be events firing, and one of them is called the "FinishedWork" event, which the business logic subscribes to. When this event is fired, it will call the method to do more work, if there is more work to be done.
I want to re-use the thread to do that work, to kind of restart that method call which has been set in the Thread.
example:
public void DoStartWork()
{
if (this.t == null)
{
this.t = new Thread(new ThreadStart(DoWork));
}
t.IsBackground = true;
t.Start();
}
//event subscription:
FinishedWork()
{
this.DoWork()
}
DoWork()
{
if (this._indexPosition < someCollection.Count)
{
//do some work
}
}
So basically, in the FinishedWork event, I want it to re-use the existing thread if possible and DoWork() on that thread, as it does the first time.
If it is not possible to restart a stopped thread, what is the best way of disposing of that thread safely without it just "laying" there?
Thanks
What is the best way of doing this? I don't want to spin up a new thread each time this "DoWork()" Method is called. I'd rather have the same thread run the same task. It will only be called when a task has finished completing.
Whats happening is this:
My business logic spins up a thread to run a method.
This method is kind of using a for loop, but not quite - basically checking the index stored globally to see if its < than a collection of items. If so, it will do some work.
There will be events firing, and one of them is called the "FinishedWork" event, which the business logic subscribes to. When this event is fired, it will call the method to do more work, if there is more work to be done.
I want to re-use the thread to do that work, to kind of restart that method call which has been set in the Thread.
example:
public void DoStartWork()
{
if (this.t == null)
{
this.t = new Thread(new ThreadStart(DoWork));
}
t.IsBackground = true;
t.Start();
}
//event subscription:
FinishedWork()
{
this.DoWork()
}
DoWork()
{
if (this._indexPosition < someCollection.Count)
{
//do some work
}
}
So basically, in the FinishedWork event, I want it to re-use the existing thread if possible and DoWork() on that thread, as it does the first time.
If it is not possible to restart a stopped thread, what is the best way of disposing of that thread safely without it just "laying" there?
Thanks