递归调用方法(用于对象重用目的)

时间:2011-04-08 20:47:38

标签: c# multithreading recursion object-pooling

  

可能重复:
  recursively calling method (for object reuse purpose)

我有一个相当大的类,其中包含大量字段(10+),一个巨大的数组(100kb)和一些处理长时间运行任务的非托管资源,我希望在每次完成任务后一遍又一遍地重复使用它。下面的代码说明了这种情况:

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);
    }

}

问题在于,DoWork在完成所有任务后永远不会返回。这导致一些点之后的库存溢出。我可以在ThreadPool上对OnComplete的调用进行排队,从而让DoWork返回并让运行时清除调用堆栈,但我不想使用额外的资源。对我来说最好的选择是什么? (假设任务进展是线性的)(DoWork必须在另一个线程上执行)

0 个答案:

没有答案