Possible Duplicate:
recursively calling method (for object reuse purpose)
i have a rather large class which contains plenty of fields (10+), a huge array (100kb) and some unmanaged resouces which process long running task and i want to reuse it over and over again after each completion of task. below code illustrates the situation:
class ResourceIntensiveClass
{
private object unmaganedResource; //let it be the expensive resource
private byte[] buffer = new byte[1024 * 100]; //let it be the huge managed memory
public Action<ResourceIntensiveClass> OnComplete;
private void DoWork(object state)
{
//do long running task
OnComplete(this); //notify callee that task completed so it can reuse same object for another task
}
public void Start(object dataRequiredForCurrentTask)
{
ThreadPool.QueueUserWorkItem(DoWork, dataRequiredForCurrentTask); //initate long runnig work
}
}
class Program
{
static object[] taskData = { "foo", "bar"};
static int currentTaskIndex = 0;
private static void OnCompleteHandler(ResourceIntensiveClass c)
{
currentTaskIndex = currentTaskIndex + 1;
if (currentTaskIndex == taskData.Length)
{
Console.WriteLine("finished all task");
return;
}
object data = taskData[currentTaskIndex];
c.Start(data);
}
public static void Main()
{
ResourceIntensiveClass c = new ResourceIntensiveClass();
c.OnComplete = OnCompleteHandler;
object data = taskData[currentTaskIndex];
c.Start(data);
}
}
The problem here is, DoWork never returns after all tasks are completed. This cause a stockoverflow after some point. i could queue invocation of OnComplete on ThreadPool thus letting the DoWork return and let the runtime clear the call stack but i dont want to use extra resources. What would be the best option for me? (assume task progression is linear)(DoWork has to be executed on another Thread)