private void renderButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; if ((string)button.Content == "Render") { ts = new CancellationTokenSource(); CancellationToken ct = ts.Token; Task.Factory.StartNew(() => { RayTracer.Scene scene = CreateScene(); if (addFloor) { RayTracer.Floor floor = new RayTracer.Floor(1, new RayTracer.Point(-10, 0, -10), new RayTracer.Point(10, 0, 10)); floor.SetProperties(0.6f, 0.4f, 0); floor.SetColors(new RayTracer.Color(0, 0, 0), new RayTracer.Color(1, 1, 1)); scene.allObjects.Add(floor); } RayTracer.Renderer renderer = new RayTracer.Renderer(scene, scene.allObjects); scene.width = RenderWidth; scene.height = RenderHeight; renderer.ct = ct; Console.WriteLine("Raytracing started."); int time = Environment.TickCount; RayTracer.RenderWindow window = renderer.Render(); if (ct.IsCancellationRequested) { return; } time = -time + Environment.TickCount; Console.WriteLine("Raytracing finished."); window.ShowImage(); Console.WriteLine("Intersection calculating time: \t" + scene.intersectionCalculationCount + "\nRender time: \t\t" + time + "ms"); window.ShowDialog(); }, ct); button.Content = "Cancel"; } else { // Can't wait anymore => cancel this task ts.Cancel(); button.Content = "Render"; } }