StackExchange.Redis异步调用挂起 [英] StackExchange.Redis async call hangs

查看:970
本文介绍了StackExchange.Redis异步调用挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出为什么这个code挂起。我可以删除在测试底部的3行中的任何一种,它不会挂起,但所有3一起使挂起。任何帮助将大大AP preciated!

  [事实]
公共异步任务CanAddValues​​InParallel(){
    VAR复用器= ConnectionMultiplexer.Connect(localhost的);
    变种分贝= muxer.GetDatabase();    等待AddAsync(DB,测试,1);
    等待db.KeyDeleteAsync(测试);    Task.Run(()=> AddAsync(DB,测试,1))。等待();
}公共异步任务<布尔> AddAsync(DB了IDatabase,串键,字符串值){
    返回等待db.StringSetAsync(键,值,空,When.NotExists);
}


解决方案

这听起来好像同步上下文僵局从混合等待等待。这就是为什么你的从不这么做 - (转换成吉尔伯特和沙利文)的 好,几乎没有!

如果有帮助,我的犯罪嫌疑人的,取消等待等待子树将修复它 - 这应该是微不足道的,因为这棵树可以用一个简单的直通取代:

 公共任务<布尔> AddAsync(DB了IDatabase,串键,字符串值){
    返回db.StringSetAsync(键,值,空,When.NotExists);
}

这里最重要的一点是,SE.Redis绕过同步上下文内部(正常库code),所以它不应该有僵局。

但最终:混合等待等待是不是一个好主意。除了死锁,这是在异步同步 - 一个反模式

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.

这篇关于StackExchange.Redis异步调用挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆