使用Tasks维护for循环中的状态

时间:2014-09-29 03:12:18

标签: c# task

每次调用Process方法时,payload.DaysRemaining值都会重置为零。

我理解包含要执行的任务的方法将独立于在其中声明的任务对象执行,这导致在包含方法中声明的变量处于松散状态。

那么如何使用依赖于方法范围变量的任务来保持for循环中的状态?

private static async Task Assign(Payload payload)
{
    var duration = payload.DaysRemainingToJobsDue.First().Key;
    var tasks = new List<Task>();

    for (var daysRemaining = duration; daysRemaining >= 0; daysRemaining--)
    {
        payload.DaysRemaining = daysRemaining;

        var task = new Task(() =>
        {
            Process(payload);
        });

        tasks.Add(task);
        task.Start();
    }

    Task.WaitAll(tasks.ToArray());
    return;
}

private static void Process(object state)
{
    var payload = state as Payload;

    foreach (var job in payload.Jobs)
    {
        var compareResult = job.DueDate.CompareTo(DateTime.Now.AddDays(payload.DaysRemaining));

        var withinRange = compareResult <= 0;

        if (withinRange)
        {
            HashSet<Job> existingJobsDue = null;
            var pendingJobsExist = payload.DaysRemainingToJobsDue.TryGetValue(payload.DaysRemaining, out existingJobsDue);

            if (pendingJobsExist)
            {
                existingJobsDue.Add(job);
            }
            else
            {
                existingJobsDue = new HashSet<Job>();
                existingJobsDue.Add(job);
            }

            payload.DaysRemainingToJobsDue[payload.DaysRemaining] = existingJobsDue;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

此效果称为closure

您需要做的是在传递给新创建的Task的lambda表达式中创建变量的本地副本:

var task = new Task(() =>
{
    var localPayload = payload;
    Process(localPayload);
});