I have the following code from 'Samples for Parallel Programming with the .NET Framework' MSDN when I was trying to cancel the Genetic generations of monkeys in debugging mode I am getting 'OperationCanceledException was unhandled by user code' on line token.ThrowIfCancellationRequested();. I have added last resort of exception handling 'UnobservedTaskException' but the code is never reaching there. Please help me in finding the problem here:
public MainForm()
{
InitializeComponent();
txtTarget.Text = _targetText;
_uiTasks = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved();
}
private int _currentIteration;
private CancellationTokenSource _cancellation;
private void btnRun_Click(object sender, EventArgs e)
{
if (_cancellation == null)
{
_cancellation = new CancellationTokenSource();
GeneticAlgorithmSettings settings = new GeneticAlgorithmSettings { PopulationSize = Int32.Parse(txtMonkeysPerGeneration.Text) };
txtBestMatch.BackColor = SystemColors.Window;
lblGenerations.BackColor = SystemColors.Control;
lblGenPerSec.Text = lblGenerations.Text = "-";
lblElapsedTime.Text = "0";
btnRun.Text = "Cancel";
chkParallel.Visible = false;
_startTime = _lastTime = DateTimeOffset.Now;
timerElapsedTime.Start();
// Run the work in the background
_cancellation = new CancellationTokenSource();
var token = _cancellation.Token;
bool runParallel = chkParallel.Checked;
Task.Factory.StartNew(() =>
{
// Create the new genetic algorithm
var ga = new TextMatchGeneticAlgorithm(runParallel, _targetText, settings);
TextMatchGenome? bestGenome = null;
// Iterate until a solution is found or until cancellation is requested
for (_currentIteration = 1; ; _currentIteration++)
{
token.ThrowIfCancellationRequested();
// Move to the next generation
ga.MoveNext();
// If we've found the best solution thus far, update the UI
if (bestGenome == null ||
ga.CurrentBest.Fitness < bestGenome.Value.Fitness)
{
bestGenome = ga.CurrentBest;
_uiTasks.StartNew(() => txtBestMatch.Text = bestGenome.Value.Text);
// If we've found the solution, bail.
if (bestGenome.Value.Text == _targetText) break;
}
}
// When the task completes, update the UI
}, token).ContinueWith(t =>
{
timerElapsedTime.Stop();
chkParallel.Visible = true;
btnRun.Text = "Start";
_cancellation = null;
switch (t.Status)
{
case TaskStatus.Faulted:
MessageBox.Show(this, t.Exception.ToString(), "Error");
break;
case TaskStatus.RanToCompletion:
txtBestMatch.BackColor = Color.LightGreen;
lblGenerations.BackColor = Color.LemonChiffon;
break;
}
}, _uiTasks.Scheduler);
}
else _cancellation.Cancel();
}
Playing with Tasks on 4.5 and got the same error but for a different reason.
Posting here as this was the top search result and it took me a while to find the cause.
try
{
await Task.Run(() => DoWork());
label1.Text = "Finished.";
}
catch (OperationCanceledException)
{
label1.Text = "Cancelled.";
}
Which ran:
private async void DoWork()
{
// WORK STUFF
{
workerCancel.Token.ThrowIfCancellationRequested();
}
}
Cancelling would cause the unhandled error because I put void instead of Task:
private async Task DoWork()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With