I'm writing a program that will perform a long-running computation, gradually improving a solution. On top of that, there's a simple UI that basically allows the user to stop the computation (letting the worker finish a step it's working on) and shows the best solution. Here's a simplified version of what I have, I'm using async/await for the first time. Is there anything you would improve, or any other comments?
Worker code
public class SearchEngine
{
//...
public async Task<IProblemSolution> Search(CancellationTokenSource cts)
{
await Task.Factory.StartNew(() => {
BestSolution = Problem.RandomSolution();
while (!cts.IsCancellationRequested)
{
IProblemSolution s = Problem.RandomSolution(); // for simplification
if (s.ObjectiveValue() < BestSolution.ObjectiveValue())
BestSolution = s;
}
});
return BestSolution;
}
}
UI
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
if (CancelTokenSrc != null)
return;
CancelTokenSrc = new CancellationTokenSource();
Engine = new SearchEngine(new SampleProblem());
StopButton.IsEnabled = true;
StartButton.IsEnabled = false;
Task<IProblemSolution> t = Engine.Search(CancelTokenSrc);
await t;
ResultLabel.Content = t.Result.ObjectiveValue().ToString();
StopButton.IsEnabled = false;
StartButton.IsEnabled = true;
CancelTokenSrc = null;
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
if (CancelTokenSrc != null)
CancelTokenSrc.Cancel();
}