1

我对测量工作室 dll 的图形(我有很少的此类实例)有疑问。在发生了几次之后,我得到Collection was modified; enumeration operation may not execute.了但异常未处理,所以我无法确切地看到它发生在哪里。我在互联网上发红是因为我没有在 UI 线程中提供图形,但我认为我不在 UI 线程之外:

private delegate void del(double press, double temp, double press1);
private object graphic_mutex = new object();
private void UpdateView(double press, double temp, double press1)
{
    if (InvokeRequired)
        Invoke(new del (UpdateView), new object[] { press , temp, press1});
    lock (graphic_mutex)
    {
        _PressionLine.PlotYAppend(press);
        _TemperatureLine.PlotYAppend(temp);
        if (_isdoublePressureSensor == true)
            _PressionLine2.PlotYAppend(press1);
    }
}

我得到的确切错误:

Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Collection was modified; enumeration operation may not execute.

你有什么想法来解决这个问题吗?

4

1 回答 1

1

您应该在调用后返回。当 InvokeRequired 为真时,您不希望代码被执行两次。代码可以直接执行,也可以通过调用执行。不是都。

private delegate void del(double press, double temp, double press1);
private object graphic_mutex = new object();
private void UpdateView(double press, double temp, double press1)
{
    if (InvokeRequired)
    {
        Invoke(new del (UpdateView), new object[] { press , temp, press1});
        return;
    }
    
    lock (graphic_mutex)
    {
        _PressionLine.PlotYAppend(press);
        _TemperatureLine.PlotYAppend(temp);
        if (_isdoublePressureSensor == true)
            _PressionLine2.PlotYAppend(press1);
    }
}

不需要锁,因为它将(必须)始终在 UI 线程上执行。

于 2021-06-18T09:53:24.327 回答