private void SetInstanceVertexBufferData() { // VB.SetData(T[]) can only be used with an array of T[] (not IList<T>). // If Instances is not a T[], then we have to copy it into an array. We // use a static shared array to avoid garbage. Only one thread can access // this array at a time. var array = Instances as T[]; if (array == null) { // Setting SharedArray is not protected because if two threads set it in parallel, // we only create garbage. lock (SharedArrayLock) { array = SharedArray; if (array == null || array.Length < Instances.Count) { array = new T[(int)MathHelper.NextPowerOf2((uint)Instances.Count - 1)]; SharedArray = array; } Instances.CopyTo(array, 0); } } var dynamicInstanceVertexBuffer = _instanceVertexBuffer as DynamicVertexBuffer; if (dynamicInstanceVertexBuffer != null) { dynamicInstanceVertexBuffer.SetData(array, 0, Instances.Count, SetDataOptions.Discard); } else { _instanceVertexBuffer.SetData(array, 0, Instances.Count); } }