private void RenderScene(DirectBitmap[] bitmaps, ITestScene scene) { var colors = new int[width * height]; var frameIndex = 0; var token = cancellationTokenSource.Token; while (WindowState != FormWindowState.Minimized && ActiveForm == this && !token.IsCancellationRequested) { currentBitmap = (currentBitmap + 1) % 2; var msg = scene.RenderScene(colors, width, height, true, cancellationTokenSource.Token); if (token.IsCancellationRequested) { break; } bitmaps[currentBitmap].SetPixels(colors); pictureBox.Image = bitmaps[currentBitmap].Bitmap; using (var gfx = Graphics.FromImage(bitmaps[currentBitmap].Bitmap)) { gfx.DrawString(Thread.CurrentThread.ManagedThreadId + ": " + msg, Font, Brushes.Black, 0, 0); } if (saveFiles) { bitmaps[currentBitmap].Bitmap.Save(Path.Combine(dirName, $"{frameIndex++:0000}.jpg"), ImageFormat.Jpeg); } if (token.IsCancellationRequested) { break; } Invoke(refresh); rayTracerScene.Animate(); rasterizationScene.Animate(); if (changed) { changed = false; scene = scene is RayTracerTestScene ? rasterizationScene : rayTracerScene; } } Interlocked.Decrement(ref threadCount); if (token.IsCancellationRequested) { Invoke(close); } }