If you need to record the pixel arrays in order, then you cannot just start a new thread for every call of this function because there is no guarantee that the threads will be run in order. The idea is to push the items into a list as quick as possible and then let another thread process the items at its own rate. This will only help with the recording part of your code, if you are trying to render more images than the UI thread can handle, then that's another issue.
void FrameArrived(object sender, byte[] pixels)
{
//push pixels into list
lock (_pixelList)
{
_pixelList.Add(pixels);
}
_waitHandle.Set();
// 1. Create a bitmap and render it on an <Image> element (UI thread).
DisplayBitmap(pixels);
// 2. Pass the byte array to a method for video recording.
//RecordBitmap(pixels);
}
AutoResetEvent _waitHandle = new AutoResetEvent(false);
List<byte[]> _pixelList = new List<byte[]>();
bool _stop = false;
void StartProcessPixelsThread()
{
Task.Run(() =>
{
while (!_stop)
{
_waitHandle.WaitOne();
while (true)
{
byte[] pixels;
lock (_pixelList)
{
if (_pixelList.Count > 0)
{
pixels = _pixelList[0];
_pixelList.RemoveAt(0);
}
else
{
break;
}
}
RecordBitmap(pixels);
}
}
});
}
void StopProcessPixelsThread()
{
_stop = true;
_waitHandle.Set();
}