2

I am using Tasks to do some processes. The tasks will be in a loop, I am not sure sure how many tasks/iterations will be there. It will vary time to time. How to use the Tasks? Below is my code.

void func1(string loc) 
{
    var CurrentDirectoryInfo = new DirectoryInfo(loc);
    Task[] tasks; // null
    int index = 0;

    foreach (DirectoryInfo D1 in CurrentDirectoryInfo.GetDirectories)
    {
        tasks[index] = Task.Factory.StartNew(() =>func1(d1.FullName));
        index++;
    }

If I use null for the Task[] tasks, I am getting Object reference not set to an instance of an object error.

If I leave it unassigned, I am getting Use of unassigned variable error.

4
  • 2
    This is very very bad code. You should re-visit your knowledge of StartNew and also decide whether you need an individual task created per directory/subdirectory. Chances are... you don't (how many cores does your PC have?). Commented Nov 28, 2013 at 4:26
  • How would you go about solving the problem if tasks were any other data type, and you were trying to access an instance method/property? Commented Nov 28, 2013 at 4:29
  • Also the root of this question has nothing to do with tasks, so it should probably be retitled and retagged. Commented Nov 28, 2013 at 4:31
  • What might be the best solution if I want to have per sub-directory, Each task takes only less than five seconds to complete. Commented Nov 28, 2013 at 4:34

1 Answer 1

1

You can use list of tasks, if you do not know how many task object you need at compile time.

List<Task> tasks = new List<Task>();

Add newly created takss in list.

foreach(DirectoryInfo D1 in CurrentDirectoryInfo.GetDirectories)
{
    tasks.Add(Task.Factory.StartNew(() =>func1(d1.FullName)));
}

The code for creating task object for directory object does not make sense. You should consider alternative approach, you might achieve this using single task in more efficient way.

Sign up to request clarification or add additional context in comments.

5 Comments

I need to wait for the tasks to finish. How Can I use the WaitAll in this case?
Yes WaitAll could be used.
How can this be done in a single thread in more effective way? I want to compute something on each task which will consume some time.
It depends on what you do in thread if processing in task is small and the task overhead is big then using single or less threads could be better approach. You can compare both after making them.
Great. So I will use the thread for the top level folders only then. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.