user3044315
user3044315

Reputation: 23

While using the Task[] Object reference not set to an instance of an object

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.

Upvotes: 2

Views: 1528

Answers (1)

Adil
Adil

Reputation: 148110

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.

Upvotes: 1

Related Questions