使用 'using' 导致在创建 EventData 列表时出现 ObjectDisposedException

Usage of 'using' causes ObjectDisposedException in creating list of EventData

我通常按如下方式将数据发送到事件中心..

var encoded = Encoding.UTF8.GetBytes(serializedString);
using (var edata = new EventData(encoded) { PartitionKey = mypkey })
{
    edata.Properties[EventDataPropertyKeys.MyKey] = myvalue;
    await _eventclient.SendAsync(edata).ConfigureAwait(false);                        
}

今天我想到尝试通过批处理发送数据,并尝试创建一个 EventData 对象列表,如下所示..

List<EventData> eventDataList = new List<EventData>();

//in a loop
var encoded = Encoding.UTF8.GetBytes(serializedString);    
using (var edata = new EventData(encoded) { PartitionKey = mypkey })
{
    edata.Properties[EventDataPropertyKeys.MyKey] = myvalue;
    eventDataList.Add(edata);
}

但是当我检查 eventdatalist 对象时,我发现 EventData 对象的 SerializedSizeInBytes 属性 显示

'This eventdata instance has already been disposed'

并且在访问 throws..

'eventData.SerializedSizeInBytes' threw an exception of type 'System.ObjectDisposedException'

真诚感谢任何帮助..

谢谢

因为在第一个代码片段中,您在 using 块内发送了 edata。但在第二个片段中,您将 edata 放入列表中,然后循环遍历列表并在 using 块之后发送每个项目,其中项目 edata 已被处理。