2

我经常发现并没有真正指定导致这种异常的确切集合。这是真的还是应该很明显?也许我只是不明白如何正确解释异常消息..

具体来说,我想知道这个。它指的是什么收藏?

事件委托的参数很简单(对象发送者),引发的事件传递空参数。尽管引发事件的类本身继承了一个列表:

public class TimeSerie : List<BarData>

这里是否清楚“集合”是指引发事件的对象,还是可以是另一个对象?可以说是动态更改的方法的事件处理程序集合吗?或者这会产生一个不同的例外吗?

    ************** Exception Text **************
System.InvalidOperationException: 
Collection was modified; enumeration operation may not execute.
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.Control.Invoke(Delegate method)
   at SomeNameSpace.SomeUserControl.InvokeOnUpdateHistory(Object sender) in D:\SomePath\SomeUserControl.cs:line 5179
   at OtherNameSpace.OtherClass.TimeSerie.HistoryUpdateEventHandler.Invoke(Object sender)

UserControl 中出现异常:

    public class SomeUserControl 

    private void InvokeOnUpdate(object sender)
    {
    this.Invoke(new GenericInvoker(Method));   // << Exception here!
    }

    private void Method() {...}

编辑: 添加了一些代码。有点简化,但认为它包括相关位。

private void Method() 
{
            if (this.instrument == null) return;  
            UnRegisterTimeSerieHandlers(this.ts);

            this.ts = instrument.DataSeries.GetTimeSerieByInterval(interval);
            if (ts != null)
            { 
                RegisterTimeseriesHandlers(ts);
                ClearAndLoadAllHistory();
            }
}

    private void UnRegisterTimeSerieHandlers(TimeSerie ts)
    {
        if (ts != null)
        {
            ts.TickUpdate -= InvokeUpdateCurrentBar;
            ts.NewBarUpdate -= InvokeUpdateNewBar;
            ts.HistoryUpdate -= InvokeOnUpdateHistory;
            this.ts = null;
        }
    }

    private void RegisterTimeseriesHandlers(TimeSerie ts)
    {
        ts.TickUpdate += InvokeUpdateCurrentBar;
        ts.NewBarUpdate += InvokeUpdateNewBar;
        ts.HistoryUpdate += InvokeOnUpdateHistory;
    }
4

2 回答 2

5

是的,当您使用 Control.Invoke() 时,可能很难诊断异常的原因。问题是当它发生在 UI 线程上时它会捕获异常并将其重新抛出到您的工作线程中。因此,您的工作线程需要知道 Invoke() 的返回值不可用。不可避免的副作用是你失去了告诉你它在哪里爆炸以及它是如何到达那里的Holy Stack Trace。

如果您可以在附加调试器时重现问题,然后使用 Debug + Exceptions,勾选 CLR Exceptions 的 Thrown 复选框。抛出异常时调试器停止,为您提供良好的语句位置和调用堆栈以查看。

如果没有,请考虑改用 Control.BeginInvoke()。这是 Invoke() 的即发即弃版本,因此如果调用的方法抛出异常,则 UI 线程将引发该异常,您将获得准确的堆栈跟踪。

一般来说,您总是希望使用 BeginInvoke()。它不会导致工作线程停止,它避免了许多死锁情况并提供良好的异常反馈。使用 Invoke() 通常是一个错误。

于 2013-01-23T00:47:11.777 回答
0

看来您正在使用计时器。也许您正在从计时器回调(另一个线程)更改一些集合(更有可能,该集合是 UI 元素的属性)而不使用Control.Invoke()调用?

于 2013-01-22T23:59:58.863 回答