I am using the code in Cancel Asynchronous Operations in C# and my code is below.
For the case of forcing a cancel, which I have to do this way because I'm calling a 3rd party library and so can't use a cancellation token down in the calls to the Salesforce API.
I believe (and my knowledge of Tasks is still very new and minimal) that in the code below, on a cancel, that my worker task will still keep running, it's just being ignored by my code going forward. Is that correct?
Or does the .NET framework kill the task even if it's in mid request to Salesforce? Either works for me, but I want to know what is going on.
private static async Task<bool> LoadMetadata(LoadingMetadata dlg, DataSourceProfile profile, CancellationToken cancellationToken)
{
// We create a TaskCompletionSource of decimal
var taskCompletionSource = new TaskCompletionSource<bool>();
// Registering a lambda into the cancellationToken
cancellationToken.Register(() =>
{
// We received a cancellation message, cancel the TaskCompletionSource.Task
taskCompletionSource.TrySetCanceled();
});
// load the metadata
Task<bool> task = Task.Run(() => { profile.ReloadMetadata(); return true; } );
// Wait for the first task to finish among the two
var completedTask = await Task.WhenAny(task, taskCompletionSource.Task);
// If the completed task is our long running operation we set its result.
bool success;
if (completedTask == task)
{
// Extract the result, the task is finished and the await will return immediately
var result = await task;
// Set the taskCompletionSource result
taskCompletionSource.TrySetResult(result);
success = true;
}
else {
Trap.trap();
success = false;
}
// close the dialog
dlg.DialogResult = success ? DialogResult.OK : DialogResult.Cancel;
dlg.Close();
// Return the result of the TaskCompletionSource.Task
return success;
}