![](/img/trans.png)
[英]How to correctly finish RabbitMq consumer and wait to RabbitMq consumer threads (library consumer callbacks) after close connection and model?
[英]Working on events with threads RabbitMQ consumer
我使用 RabbitMQ dot net 库在 C# 中的不同队列上有两个使用者。
我想要的是:
由于某些业务逻辑,我必须在一个消费者中等待一段时间,因此我为此使用了Thread.Sleep()
问题
如果我在一个事件中使用Thread.Sleep
,第二个线程也不会暂停
我的代码:
consumer.Received += (model, ea) =>
{
try
{
DRModel drModel = JsonConvert.DeserializeObject<DRModel>(Encoding.UTF8.GetString(ea.Body));
RMQReturnType type = ProcessSubmitSMS(drModel);
if (type == RMQReturnType.ACK)
channel.BasicAck(ea.DeliveryTag, false);
else
{
channel.BasicNack(ea.DeliveryTag, false, true);
Thread.Sleep(300000); // <=== SLEEP
}
}
catch (Exception ex)
{
channel.BasicNack(ea.DeliveryTag, false, true);
WriteLog(ControlChoice.ListError, "Exception: " + ex.Message + " | Stack Trace: " + ex.StackTrace.ToString() + " | [Consumer Event]");
}
};
对于Mutex类来说,这似乎是一个很好的例子,您需要的是多线程中的条件睡眠。 不确切知道您需要的逻辑,但您的代码类似于以下代码:
public class Consumer
{
public event EventHandler Received;
public virtual void OnReceived()
{
Received?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
static void Main(string[] args)
{
var mutex = new Mutex();
var consumer = new Consumer();
consumer.Received += (model, ea) =>
{
try
{
mutex.WaitOne();
var id = Guid.NewGuid().ToString();
Console.WriteLine($"Start mutex {id}");
Console.WriteLine($"Mutex finished {id}");
Console.WriteLine($"Start sleep {id}");
if ( new Random().Next(10000) % 2 == 0) // randomly sleep, that your condition
{
Thread.Sleep(3000); // <=== SLEEP
}
Console.WriteLine($"Sleep finished {id}");
}
catch (Exception ex)
{
mutex.ReleaseMutex(); // this is where you release, if something goes wrong
}
finally
{
mutex.ReleaseMutex();// always release it
}
};
Parallel.For(0, 10, t => //running 10 threads in parallel and stops all if the condition is true
{
consumer.OnReceived();
});
Console.ReadLine();
}
}
}
我的代码中有一些逻辑错误,我理解。 在rabbitmq中,我在两个不同的频道上创建了两个消费者事件,所以我认为它不会在这里共享我错了一个连接是共享的黑白频道所以我明确地定义了两个连接。 据我了解,消费者块通道和通道块连接和连接在两个事件中都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.