Search code examples
c#azureazure-eventhub

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


I normally send data to event hub as follows..

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);                        
}

Today I thought of trying to send the data via batch and tried to create a list of EventData objects as follows..

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);
}

But when I check the eventdatalist objects, I find SerializedSizeInBytes property of EventData object showing

'This eventdata instance has already been disposed'

and while accessing throws..

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

Any help is sincerely appreciated..

Thanks


Solution

  • Because in the first code snippet, you send edata inside the using block. But in the second snippet, you put edata in a list, and after that, loop through the list and send each item after the using block, where the item edata is already disposed.