If you want your measurement processing to be cancellable you must make it aware of some sort of cancellation flag. Alternative is to cancel it (abort) in an non-compliant way but that is highly discouraged because you could stop your processing in a middle of something important and without giving it a chance to clean up or free resources.
Instead of BackgroundWorker
you could use Task Parallel Library and then code could look like this:
CancellationTokenSource cts = new CancellationTokenSource();
Task tsk = Task.Factory.StartNew(() =>
{
Measurement measurement = new Measurement();
measurement.Execute(cts.Token);
},
cts.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
where Execute
might look something like this:
public void Execute(CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
while (true)
{
// processing
// ...
// need to cancel?
ct.ThrowIfCancellationRequested();
}
}
To cancel call this in main thread:
cts.Cancel();
You will get TaskCancelledException
but that is expected.
Alternatively, if you do not want exception use the following version of Execute
. It is not strictly per TPL guidelines but it will work fine if you do not use conditional continuations.
public void Execute(CancellationToken ct)
{
if (ct.IsCancellationRequested)
return;
while (true)
{
// processing
if (ct.IsCancellationRequested)
return;
}
}