传递参数不断变化值任务 - 行为? [英] Passing arguments with changing values to Task -- Behaviour?

查看:122
本文介绍了传递参数不断变化值任务 - 行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情景:在一个循环中的异步任务执行包含更改参数的方法,程序继续:

Scenario: An asynchronous task in a loop executes a method containing arguments that change as the program continues:

while(this._variable < 100)
{
    this._variable++; 
    var aTask = Task.Factory.StartNew(() =>
    {
        aList.add(this._variable);
        update(this._savePoint);
    });
}

如果环路的运行速度比的任务完成后,将更快列表中添加该变量的当前值或是保存在本地变量并加到原始值α

If the loop runs faster than the tasks complete, will the list add the current value of the variable or is the variable saved locally and the original value added?

推荐答案

瓶盖封盖的变量,而不是价值。因此,递增 _variable 可以的修改,指的是任务的行为。

Closures close over variables, not values. Therefore, incrementing _variable can alter the behavior of the task that refers to it.

您可以通过一个本地副本prevent这样的:

You can prevent this by making a local copy:

while (this._variable < 100)
{
    this._variable++;
    int local = _variable;
    var aTask = Task.Factory.StartNew(() =>
    {
        aList.add(local);
        update(this._savePoint);
    });
} 

或者你可以在值传递给任务的状态:

Or you could pass the value to the task as state:

while (this._variable < 100)
{
    this._variable++;
    var aTask = Task.Factory.StartNew(object state =>
    {
        aList.add((int)state);
        update(this._savePoint);
    }, this._variable);
} 

这些工作既通过复制 _variable 的值到一个新的临时变量。在第一种情况下,本地变量定义在循环的范围内,所以你得到一个新的每次迭代。在第二种情况下,你让 _variable ,当你把它传递到任务的状态值的副本论据。如果 _variable 是引用类型,这些解决方案是行不通的;你必须进行克隆。

These both work by copying the value of _variable to a new temporary variable. In the first case the local variable is defined inside the scope of the loop, so you get a new one for every iteration. In the second case, you make a copy of the value of _variable when you pass it to the Task as the state argument. If _variable were a reference type, these solutions wouldn't work; you'd have to perform a clone.

这篇关于传递参数不断变化值任务 - 行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆