Странный “Набор был изменен после того, как перечислитель инстанцировали” исключение

Предполагая, что у вас есть определенные требования для использования частичного представления, вы можете найти, как перезагрузить в этой статье . Посмотрите на второй ответ, который лучше.

Теперь, если вы хотите только заполнить диаграмму, почему бы просто не вызвать функцию «createchart» снова после изменения ваших данных в файле .js? Тогда вам вообще не придется использовать частичное представление.

jQuery(document).ready(function() {
  $("#Partitionbox").change(function() {
    var id = $(this).find(":selected").text()
    var selectid = {
      "id": id
    }

    $.ajax({
      url: '@Url.Action("RefreshView")',
      data: JSON.stringify(selectid),
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      success: function(data) {
        // Variable data contains the data you get from the action method
        //$('#DPartition').load(data);

        createchart(data);
      },


    });
  });

  var w = 600,
    h = 400,
    x = d3.scale.linear().range([0, w]),
    y = d3.scale.linear().range([0, h]);
  var vis = d3.select("#top").append("div")
    .attr("class", "chart")
    .style("width", w + "px")
    .style("height", h + "px")
    .append("svg:svg")
    .attr("width", w)
    .attr("height", h);
  var partition = d3.layout.partition()
    .value(function(d) {
      return d.size;
    });

  var data = flare;

  createchart(data);

  function refreshview() {
    setInterval(function() {
      $('#contributors').load('/Home/GetContributor');
    }, 10000); // every 3 sec
  };

  function createchart(root) {
    var g = vis.selectAll("g")
      .data(partition.nodes(root))
      .enter().append("svg:g")
      .attr("transform", function(d) {
        return "translate(" + x(d.y) + "," + y(d.x) + ")";
      })
      .on("click", click);
    var kx = w / root.dx,
      ky = h / 1;
    g.append("svg:rect")
      .attr("width", root.dy * kx)
      .attr("height", function(d) {
        return d.dx * ky;
      })
      .attr("class", function(d) {
        return d.children ? "parent" : "child";
      });
    g.append("svg:text")
      .attr("transform", transform)
      .attr("dy", ".35em")
      .style("opacity", function(d) {
        return d.dx * ky > 12 ? 1 : 0;
      })
      .text(function(d) {
        return d.name + ": $" + d.size;
      })
    d3.select(window)
      .on("click", function() {
        click(root);
      })

    function click(d) {
      if (!d.children) return;
      kx = (d.y ? w - 40 : w) / (1 - d.y);
      ky = h / d.dx;
      x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
      y.domain([d.x, d.x + d.dx]);
      var t = g.transition()
        .duration(d3.event.altKey ? 7500 : 750)
        .attr("transform", function(d) {
          return "translate(" + x(d.y) + "," + y(d.x) + ")";
        });
      t.select("rect")
        .attr("width", d.dy * kx)
        .attr("height", function(d) {
          return d.dx * ky;
        });
      t.select("text")
        .attr("transform", transform)
        .style("opacity", function(d) {
          return d.dx * ky > 12 ? 1 : 0;
        });
      d3.event.stopPropagation();
    }

    function transform(d) {
      return "translate(8," + d.dx * ky / 2 + ")";
    }
  };

  document.getElementById('footer').append(footer);
  var ele = document.createElement("div");
  ele.classList.add("hint");
  ele.append(hint);
  document.getElementById('footer').appendChild(ele);
});
@Html.Partial("SPPDVis1") @Html.Partial("SPPDVis2")
@Html.Partial("SPPDVis3") @Html.Partial("SPPDVis4")
@Html.DropDownList("Partitionbox", Model.Countries, "Select Country")

Надеюсь, что смогу хоть немного помочь. Удачного кодирования:)

12
задан gturri 26 May 2014 в 12:11
поделиться

3 ответа

I suspect the place to start looking will be at any places where you manipulate the list - i.e. insert/remove/re-assign items. My suspicion is that there will be a callback/even-handler somewhere that is getting fired asynchronously (perhaps as part of the XNA paint etc loops), and which is editing the list - essentially causing this problem as a race condition.

To check if this is the case, put some debug/trace output around the places that manipulate the list, and see if it ever (and in particular, just before the exception) runs the manipulation code at the same time as your console output:

private void SomeCallback()
{
   Console.WriteLine("---Adding foo"); // temp investigation code; remove
   components.AddLast(foo);
   Console.WriteLine("---Added foo"); // temp investigation code; remove
}

Unfortunately, such things are often a pain to debug, as changing the code to investigate it often changes the problem (a Heisenbug).

One answer would be to synchronize access; i.e. in all the places that edit the list, use a lock around the complete operation:

LinkedList<Component> components = new LinkedList<Component>();
readonly object syncLock = new object();
...
private void PrintComponentList()
{
    lock(syncLock)
    { // take lock before first use (.Count), covering the foreach
        Console.WriteLine("---Component List: " + components.Count
              + " entries---");
        foreach (Component c in components)
        {
           Console.WriteLine(c);
        }
        Console.WriteLine("------");
    } // release lock
}

and in your callback (or whatever)

private void SomeCallback()
{
   lock(syncLock)
   {
       components.AddLast(foo);
   }
}

In particular, a "complete operation" might include:

  • check the count and foreach/for
  • check for existance and insert/remove
  • etc

(i.e. not the individual/discrete operations - but units of work)

11
ответ дан 2 December 2019 в 19:55
поделиться

Вместо foreach я использую while (collection.count> 0) , затем использую collection [i] .

4
ответ дан 2 December 2019 в 19:55
поделиться

Я не знаю, относится ли это к OP, но у меня была такая же ошибка, и я нашел эту ветку во время поиска в Google. Я смог решить эту проблему, добавив перерыв после удаления элемента в цикле.

foreach( Weapon activeWeapon in activeWeapons ){

            if (activeWeapon.position.Z < activeWeapon.range)
            {
                activeWeapons.Remove(activeWeapon);
                break; // Fixes error
            }
            else
            {
                activeWeapon.position += activeWeapon.velocity;
            }
        }
    }

Если вы пропустите перерыв, вы получите ошибку «InvalidOperationException: Коллекция была изменена после создания экземпляра перечислителя».

2
ответ дан 2 December 2019 в 19:55
поделиться
Другие вопросы по тегам:

Похожие вопросы: