c# - 运行多个任务重用同一个对象实例

标签 c# concurrency task

这是一个有趣的。我有一个创建一堆 Task 的服务。目前列表中只配置了两个任务。但是,如果我在 Task 操作中放置一个断点并检查 schedule.Name 的值,则会使用相同的计划名称命中两次。但是,在计划列表中配置了两个单独的计划。谁能解释为什么任务重用循环中的最后一个时间表?这是范围问题吗?

// make sure that we can log any exceptions thrown by the tasks
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);

// kick off all enabled tasks
foreach (IJobSchedule schedule in _schedules)
{
    if (schedule.Enabled)
    {
        Task.Factory.StartNew(() =>
                                {
                                    // breakpoint at line below. Inspecting "schedule.Name" always returns the name 
                                    // of the last schedule in the list. List contains 2 separate schedule items.
                                    IJob job = _kernel.Get<JobFactory>().CreateJob(schedule.Name);
                                    JobRunner jobRunner = new JobRunner(job, schedule);
                                    jobRunner.Run();
                                },
                                CancellationToken.None, 
                                TaskCreationOptions.LongRunning, 
                                TaskScheduler.Default
                                );
    }
} // next schedule

最佳答案

如果您在 foreach 循环中使用临时变量,它应该可以解决您的问题。

foreach (IJobSchedule schedule in _schedules)
{
    var tmpSchedule = schedule;
    if (tmpSchedule.Enabled)
    {
        Task.Factory.StartNew(() =>
                                {
                                    // breakpoint at line below. Inspecting "schedule.Name" always returns the name 
                                    // of the last schedule in the list. List contains 2 separate schedule items.
                                    IJob job = _kernel.Get<JobFactory>().CreateJob(tmpSchedule.Name);
                                    JobRunner jobRunner = new JobRunner(job, tmpSchedule);
                                    jobRunner.Run();
                                },
                                CancellationToken.None, 
                                TaskCreationOptions.LongRunning, 
                                TaskScheduler.Default
                                );
    }


} //

有关闭包和循环变量的进一步引用,请参阅 Closing over the loop variable considered harmful

关于c# - 运行多个任务重用同一个对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15245679/

相关文章:

c# - 如何让 TagLib# 处理扩展名错误的文件?

c# - 升级后删除以前版本的用户设置配置文件和目录 C#

c# - Asp.Net核心: call a custom method after response is returned from another middleware

Java Swing 应用程序 : how to get data from the GUI thread to another thread?

c# - OnlyOnRanToCompletion 和 NotOnFaulted 之间的区别?

c# - Mono.Cecil 是否负责分支机构等位置?

java - 等待子线程完成,而不引用该线程

java - 同时添加到 ArrayList 的并发线程 - 会发生什么?

c# - 异步/等待抛出未处理的异常

python - 具有非同质任务的 Celery