public async Task CalculateBB() { ClearTextBox(); cts[0].Cancel(); cts[0] = new CancellationTokenSource(); int maxTime; if (!Int32.TryParse(textB_timeBB.Text, out maxTime)) { textB_timeBB.Background = Brushes.Coral; errorTB.Push(textB_timeBB); return; } BB algorithm = null; Stopwatch time = null; Location[] solve = null; Task thisTask = (Task.Run(() => { algorithm = new BB(maxTime); time = new Stopwatch(); time.Start(); solve = algorithm.Solution(cities); time.Stop(); })); tasks.Enqueue(thisTask); await Task.Run(() => { while (true) { if (cts[0].Token.IsCancellationRequested || thisTask.IsCompleted) { break; } } }); if (solve != null) { DrawLines(solve, graphs); timeBB.Content = time.ElapsedMilliseconds; lengthBB.Content = Math.Round(algorithm.TotalDistance, 2); } }