0

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;
    }
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • Yes! The runtime doesn't stop the tasks. – Paulo Morgado Jan 02 '20 at 12:10
  • I linked a dup answer that gets to the heart of your question about the remaining tasks. But with regard to cancellation, understand that cancelling a task is not the same as killing a thread (because a task is not a thread). Cancellation has to be handled explicitly by the code in the task (eg: by checking `token.IsCancellationRequested` or calling `token.ThrowIfCancellationRequested`). If the code you're calling has no cancellation mechanism, then there's not much you can do. Even if you used a new thread, would you really want to just kill that thread without knowing what state it was in? – Matt Johnson-Pint Jan 02 '20 at 20:06

0 Answers0