private void AsyncDraw(AlgorithmProcessor algorithmProcessor, Complex center, double radius, int width, int height) { if (tokens.Count > 0 && !tokens.Peek().IsCancellationRequested) { tokens.Peek().Cancel(); //tokens.Peek().Dispose(); ++currentTaskID; } var token = new CancellationTokenSource(); tokens.Push(token); Task.Factory.StartNew(() => { algorithmProcessor.GetBitmapSourceFromComplexGrid( center, radius, width * 2, height * 2, currentTaskID, Report, token.Token); }, token.Token).ContinueWith(new Action <Task>(t => t.Dispose()), token.Token); void Report(BitmapSourceResult result) { Application.Current?.Dispatcher.BeginInvoke(new Action(() => { if (!token.IsCancellationRequested && (Fractal.Tag == null || result.taskID != ((BitmapSourceResult)Fractal.Tag).taskID || result.timesSmaller < ((BitmapSourceResult)Fractal.Tag).timesSmaller)) { lock (Fractal) { Fractal.Source = result.bitmap; Fractal.Tag = result; } } })); } // end Report } // end AsyncDraw
private void ComputeFractal() { if (Settings.Instance.Center == null || double.IsNaN(Fractal.Width) || double.IsNaN(Fractal.Height) || Fractal.Width == 0 || Fractal.Height == 0) { return; } var fractalFactory = new ComplexFractalFactory(); Colorer = new AlgorithmProcessor(fractalFactory.GetAutoConfiguredAlgorithmByID((Algorithm)Settings.Instance.algorithm, AlgorithmFunction ?? Function)); AsyncDraw(Colorer, Settings.Instance.Center, Settings.Instance.Radius, (int)Fractal.Width, (int)Fractal.Height); Status.Text = $"Radius={Settings.Instance.Radius}"; }