Bug 4173 - Deadlock cancelling task when task has continuation dependent on same cancellation token, or synchronous execution
Summary: Deadlock cancelling task when task has continuation dependent on same cancell...
Status: RESOLVED FIXED
Alias: None
Product: Class Libraries
Classification: Mono
Component: System ()
Version: 2.10.x
Hardware: PC Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Jérémie Laval
URL:
Depends on:
Blocks:
 
Reported: 2012-04-01 03:37 UTC by MartinG
Modified: 2012-04-10 07:41 UTC (History)
4 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED FIXED

Description MartinG 2012-04-01 03:37:11 UTC
The following test will deadlock:

            var cancellationTokenSource = new CancellationTokenSource();
            var ct = cancellationTokenSource.Token;

            var tcs = new TaskCompletionSource<object>();

            // Whenever the cancellation token is cancelled, cancel the task completion source.
            ct.Register(() => tcs.TrySetCanceled());

            // Add a continuation that performs some function after the task completion source completes
            tcs.Task.ContinueWith(
                _ => Console.WriteLine ("Should not get here"),
                ct,
                TaskContinuationOptions.OnlyOnRanToCompletion,
                TaskScheduler.Default);

            // The following line will deadlock
            cancellationTokenSource.Cancel();

            Console.WriteLine("Doesn't get to this line.");
Comment 1 MartinG 2012-04-01 04:35:53 UTC
The following code also deadlocks (followed by application crash later):
        [Test]
        public void CancellationDeadlockSyncTask()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var ct = cancellationTokenSource.Token;

            Task.Factory.StartNew(() => {
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }).ContinueWith(_ => Console.WriteLine("In continuation"), ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)
                .ContinueWith(_ => Console.WriteLine("In continuation2"), ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

            cancellationTokenSource.Cancel();

            Console.WriteLine("Doesn't get to this line.");
        }

If there are multiple continuations with the same cancellation token and either conditions on the continuation or synchronous execution, then this deadlocks.

Problem is that when the task represented by the continuation is cancelled it cannot remove its registration from the cancellation token source due to a "lock" being held.
Comment 2 MartinG 2012-04-01 04:58:33 UTC
Simplist example (note there are two code paths which also cause this issue, conditions on continuation and executing synchronously):

        [Test]
        public void SimpleCancellationTest()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var ct = cancellationTokenSource.Token;

            var task = new Task(() => {}, ct).ContinueWith(_ => {}, ct, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
            // Also var task = new Task(() => {}, ct).ContinueWith(_ => {}, ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

            cancellationTokenSource.Cancel();

            Console.WriteLine("Doesn't get to this line.");
        }
Comment 3 Rolf Bjarne Kvinge [MSFT] 2012-04-02 17:52:54 UTC
Jéremie, I think this is your area.
Comment 4 MartinG 2012-04-03 08:29:00 UTC
I have created a patch against master. This changes the behavior to allow cancellation registrations to be removed while other cancellations are being processed. Otherwise behavior should be exactly as it was before.

Patch and test case at:
http://github.com/mgranell/mono/commit/87ad22dbdfedd1b7b3efd57526f03588377e0d7d
Comment 5 Jérémie Laval 2012-04-03 08:57:47 UTC
Thanks for the test cases and patch, I will review your changes this week.
Comment 6 Jérémie Laval 2012-04-10 07:41:00 UTC
Fixed in master. Thanks for the report!