Skip to content

Commit

Permalink
Fix for synchronous cancellation bug https://bugzilla.xamarin.com/sho…
Browse files Browse the repository at this point in the history
  • Loading branch information
marting committed Apr 3, 2012
1 parent 1b09033 commit 87ad22d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 25 deletions.
58 changes: 34 additions & 24 deletions mcs/class/corlib/System.Threading/CancellationTokenSource.cs
Expand Up @@ -126,26 +126,44 @@ public void Cancel (bool throwOnFirstException)

List<Exception> exceptions = null;

// Allow callbacks to be removed during the processing
// of the set of callbacks.
CancellationTokenRegistration[] localCallbacks;
lock (syncRoot) {
try {
foreach (var item in callbacks) {
if (throwOnFirstException) {
item.Value ();
} else {
try {
item.Value ();
} catch (Exception e) {
if (exceptions == null)
exceptions = new List<Exception> ();
localCallbacks = new CancellationTokenRegistration[callbacks.Count];
callbacks.Keys.CopyTo(localCallbacks, 0);
}
try {
foreach (var registration in localCallbacks) {
Action callback;
lock (syncRoot) {
callbacks.TryGetValue(registration, out callback);
}

exceptions.Add (e);
}
if (callback == null) {
continue;
}

if (throwOnFirstException) {
callback ();
} else {
try {
callback ();
} catch (Exception e) {
if (exceptions == null)
exceptions = new List<Exception> ();

exceptions.Add (e);
}
}
} finally {
callbacks.Clear ();
}
}
finally {
lock (syncRoot) {
callbacks.Clear();
}
}

Thread.MemoryBarrier ();
processed = true;
Expand Down Expand Up @@ -265,19 +283,11 @@ internal CancellationTokenRegistration Register (Action callback, bool useSynchr

internal void RemoveCallback (CancellationTokenRegistration tokenReg)
{
if (!canceled) {
if (!processed) {
lock (syncRoot) {
if (!canceled) {
callbacks.Remove (tokenReg);
return;
}
callbacks.Remove (tokenReg);
}
}

SpinWait sw = new SpinWait ();
while (!processed)
sw.SpinOnce ();

}
}
}
Expand Down
2 changes: 1 addition & 1 deletion mcs/class/corlib/corlib_test.dll.sources
Expand Up @@ -468,4 +468,4 @@ System.Threading/CountdownEventTests.cs
System/AggregateExceptionTests.cs
System.Threading/ThreadLocalTests.cs
System.Threading/SpinLockTests.cs

System.Threading.Tasks/TaskCancellationTest.cs

0 comments on commit 87ad22d

Please sign in to comment.