1

I want to wrap Task class, but when I run my code it throw ArgumentOutOfRangeException. It’s strange because when I’m using debugger no exception has been thrown. Here is ‘working’ example of my code.

public class TaskService
{
private Task<int>[] _tasks;
private List<DateTime> _arguments = new List<DateTime>();

public void AddArgument(DateTime argument)
{
    _arguments.Add(argument);
}

public void RunTask(Func<DateTime, int> doWork)
{
    _tasks = new Task<int>[_arguments.Count];

    for (int i = 0; i < _arguments.Count; i++)
    {
        _tasks[i] = Task.Factory.StartNew<int>(() => doWork(_arguments[i])); // Exception is throwing here: _arguments[i]
        // by some reason i = 2, but _arguments.Count = 2 so it should never happed
    }
}

public void Wait()
{
    Task.WaitAll(_tasks);
}
}

class Program
{
static void Main(string[] args)
{
    TaskService taskService = new TaskService();

    taskService.AddArgument(new DateTime(2014, 1, 1));
    taskService.AddArgument(new DateTime(2014, 2, 1));
    taskService.RunTask(DoWork);
    taskService.Wait();
}

public static int DoWork(DateTime day)
{
    Console.WriteLine(day);
    return 0;
}
}
1
  • use i<_arguments.Count - 1 Commented Apr 16, 2014 at 15:06

1 Answer 1

4

Your problem occurs because of the closure (further reading). The i variable is captured within the lambda. After you finish creating tasks (after the loop) value of i is 2. And when the tasks start, they are still referring to this particular int instance. Try this:

public void RunTask(Func<DateTime, int> doWork)
{
    _tasks = new Task<int>[_arguments.Count];

    for (int i = 0; i < _arguments.Count; i++)
    {
        var index = i;
        _tasks[i] = Task.Factory.StartNew<int>(() => doWork(_arguments[index]));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.