Possible deadlock in CompletionManager
According to documentation the "TaskSource.CreateDenyExecSync" will "Create a new TaskCompletionSource that will not allow result-setting threads to be hijacked". But the actual implementation doesn't do that, i.e. it return TaskCompletionSource which executes continuations in result-setting threads.
Here is example of deadlock that happens because of this bug. Environment: dot.net 4.5.0, 4.6.0 StackExchange.Redis 1.2.0, 1.2.1
static void Main(string[] args)
{
Task.Run(CreateDeadlockAsync).Wait();
Console.WriteLine("Finish");
}
static async Task CreateDeadlockAsync()
{
using (var conn = ConnectionMultiplexer.Connect("localhost"))
{
var db = conn.GetDatabase();
RedisKey key = "anykey";
// Somehow the deadlock doesn't happen for small payloads
// So create large payload
await db.StringSetAsync(key, new string('A', 10000000)).ConfigureAwait(false);
await db.StringGetAsync(key).ConfigureAwait(false);
Task.Run(
async () => await db.StringGetAsync(key).ConfigureAwait(false)
)
// create deadlock by blocking current thread
// i.e. all calls of CompletionManager.ProcessAsyncCompletionQueueImpl
// will wait until current thread finish execution
.Wait();
}
}
To fix this for dot.net 4.6 the CreateDenyExecSync should be changed to:
/// <summary>
/// Create a new TaskCompletionSource that will not allow result-setting threads to be hijacked
/// </summary>
public static TaskCompletionSource<T> CreateDenyExecSync<T>(object asyncState)
{
#if PLAT_SAFE_CONTINUATIONS
return new TaskCompletionSource<T>(asyncState, TaskCreationOptions.RunContinuationsAsynchronously);
#else
var source = new TaskCompletionSource<T>(asyncState);
//DenyExecSync(source.Task);
return source;
#endif
}
Maybe I'm not looking in the right places, but I'm not actually seeing PLAT_SAFE_CONTINUATIONS defined for any build configurations.
Although maybe this bug explains why there were issues when trying to use RunContinuationsAsync?
The code for PLAT_SAFE_CONTINUATIONS has since been removed and we do dynamic detection at runtime - which works around some of the issues that create problems no matter which path is chosen. Some of the underlying issues got resolved in .NET 4.6.2, though.
Going to close this out since the landscape has changed and while you can still intentionally create a deadlock (you can without the lib at all), that's a distinct issue from the platform safe continuations :)