I’m using C# Channels in important performance environment (using as camera frame buffer). As I have been testing is the fastest option to do that.
I have a little doubt on how to close the Channel.
I have a producer thread which is adding elements to channel, but If I unsuscribe to an event I want to close the channel to free resources and remove the consummer task.
The key here is how to close the channel without having exceptions when other thread have to write on the Channel.
private event EventHandler<> _frameSetEvent;
public event EventHandler<> FrameSetEvent
{
add
{
StartBmpFrameBuffer();
_frameSetEvent += value;
}
remove
{
_frameSetEvent -= value;
_frameBuffer.CloseBuffer(); //Channel Complete
}
}
I can check before adding, but I don’t know really the performance impact on the if check
public async Task AddItemAsync(T item)
{
if (_bufferRunning)
await _mainChannel.Writer.WriteAsync(item);
}
Here is my code to add. I think that maybe in the sentences after the if the close buffer can come from other thread and make the adding fail (if remove the checking on the add)
private async Task AddCamFrameSet2BmpBuffer(CvCameraFrameSetEvtArgs camFrameSet)
{
if (_frameSetEvent != null)
{
if (_frameBuffer == null)
return;
//Some code (not too long) (maybe 1-2 ms)
await _frameBuffer.AddItemAsync(camVisionFrameSet);
}
}
I was asking because maybe there is a better and efficient way to close the channel without having problems with producer.