简体   繁体   中英

StackExchange.Redis async call hangs

Trying to figure out why this code hangs. I can remove any one of the 3 lines at the bottom of the test and it won't hang, but all 3 together makes it hang. Any help would be greatly appreciated!

[Fact]
public async Task CanAddValuesInParallel() {
    var muxer = ConnectionMultiplexer.Connect("localhost");
    var db = muxer.GetDatabase();

    await AddAsync(db, "test", "1");
    await db.KeyDeleteAsync("test");

    Task.Run(() => AddAsync(db, "test", "1")).Wait();
}

public async Task<bool> AddAsync(IDatabase db, string key, string value) {
    return await db.StringSetAsync(key, value, null, When.NotExists);
}

It sounds to me like a sync-context deadlock from mixing Wait and await . Which is why you never do that - (switching into "Gilbert and Sullivan"): well, hardly ever!

If it helps, I suspect that removing the await in the Wait subtree will fix it - which should be trivial since that tree can be replaced with a trivial pass-thru:

public Task<bool> AddAsync(IDatabase db, string key, string value) {
    return db.StringSetAsync(key, value, null, When.NotExists);
}

The important point here is that SE.Redis bypasses sync-context internally (normal for library code), so it shouldn't have the deadlock.

But ultimately: mixing Wait and await is not a good idea. In addition to deadlocks, this is "sync over async" - an anti-pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM