0

I am developing a C# class where I am allocated an array buffer, and each time an event fires, I am populating the next element in my array. So for example:

class MyClass
{
    private int[] buffer = new int[10];
    private int index = 0;

    public void EventFired(object sender, IntEventArgs e)
    {
        buffer[index] = e.Integer;
        index++;
    }
}

If I have multiple events that are firing within rapid succession of one another, say every 0.5-1.0 ms, will EventFired populate the array in the order which the events were fired? What if instead of storing one integer every time the event fires, I was storing 2,000 or 10,000 integers? Do I need to be worried about race conditions?

I'm not that familiar with the inner workings of C#/.NET so would love any advice on how to guarantee that we populate buffer in the same order in which the events fired chronologically.

ArKi
  • 681
  • 1
  • 10
  • 22
  • You should be worried about race conditions. If I were you I would use `lock`. – Ali Bahrami Nov 30 '16 at 07:40
  • take a look on these pages: http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety and http://stackoverflow.com/questions/16216400/c-sharp-events-execution-are-thread-safe – Ali Bahrami Nov 30 '16 at 07:43
  • 2
    All your events are fired only from UI Thread or from several background threads? – 3615 Nov 30 '16 at 07:53
  • @3615 So the actual problem I am working with is that I have a class called CameraManager that captures individual images and raises the event ImageCapturedEvent. It captures images at 1,000-2,000 FPS, but there is only one instance of the class firing the event. I would like to stitch these individual images in a class called ImageManager, which handles these events and copies the individual images into a larger image. – ArKi Nov 30 '16 at 08:08
  • If you are subscribing to ImageCapturedEvent in your app main thread(no other threads are created), then events will be processed consequently, in the order they are coming, because there is no multithreading. To have multithreading you must have several threads that have processing classes which are subscribed to your event. – 3615 Nov 30 '16 at 08:24

1 Answers1

0

If you use a ConcurrentQueue<int>, you will have a first-in, first-out solution that is thread safe.

Frank
  • 431
  • 1
  • 5
  • 25