[英]Working on events with threads RabbitMQ consumer
I have two consumer on different queues in C# using RabbitMQ dot net library.我使用 RabbitMQ dot net 库在 C# 中的不同队列上有两个使用者。
What i want:我想要的是:
Because of some business logic, I have to wait for some time in one consumer so i have used Thread.Sleep()
for that purpose由于某些业务逻辑,我必须在一个消费者中等待一段时间,因此我为此使用了Thread.Sleep()
Problem问题
if I use Thread.Sleep
in one event the second thread is also not paused如果我在一个事件中使用Thread.Sleep
,第二个线程也不会暂停
My code:我的代码:
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]");
}
};
It seems it is a good case for Mutex class, what you need is a conditional sleep in multithreading.对于Mutex类来说,这似乎是一个很好的例子,您需要的是多线程中的条件睡眠。 Don't know exactly the logic that you need, but thy something like the code below:不确切知道您需要的逻辑,但您的代码类似于以下代码:
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();
}
}
} }
there is some logical error in my code whcih i understand.我的代码中有一些逻辑错误,我理解。 In rabbitmq i have created two consumer events on two different channels so i thought it will not be shared here i was wrong a connection was shared b/w channels so i explicly defin two connection for that.在rabbitmq中,我在两个不同的频道上创建了两个消费者事件,所以我认为它不会在这里共享我错了一个连接是共享的黑白频道所以我明确地定义了两个连接。 as i understand consumer block channel and channel block connection and connection is same in both events.据我了解,消费者块通道和通道块连接和连接在两个事件中都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.