Trying to remove an edge

Topics: bug
Nov 18, 2010 at 4:07 PM

We have a situation where some vertex has more than one edge. When we try to remove one of the edges, we get an exception from a Code Contract.

          IEdge<object> edge;
          if (_graphToVisualize.TryGetEdge(sVertex, tVertex, out edge))
          {
            if (edge != null)
            {
              _dispatcher.BeginInvoke((Action)(() =>
              {
                try
                {
                  _graphToVisualize.RemoveEdge(edge);
                }
                catch (Exception ex)
                {
                  Console.WriteLine("Error removing OUT edge, {0}", ex.Message);
                }
              }));
            }
          }
Resulting error:
A first chance exception of type 'System.Diagnostics.Contracts.__ContractsRuntime.ContractException' occurred in QuickGraph.dll
Error removing OUT edge, Precondition failed: e != null

Is there a contract that I can remove to allow this?

Thanks!
Coordinator
Nov 18, 2010 at 10:45 PM

You need to be careful with closures in C#. The side effects of TryGetEdge are visible in the lambda expression execute by the _dispatcher. Do:

var e = edge;
_dispatcher.BeginInvoke((Action)(() => {
  try { _graphToVisualize.RemoveEdge(e); } ...

Nov 19, 2010 at 6:20 PM

Thanks, pelikhan, that worked!