C#线程间通信线程、通信

2023-09-04 02:43:37 作者:江山不敌你

您好我想线程协作生产者和消费者。 消费者是相当缓慢,而生产商是非常快的,工作在突发。

例如,消费者可以处理一个消息每20秒,生产者可以在一秒钟内产生10的消息,但在相当长的做它约一次,同时使消费者可以赶上

我想是这样的:

 流commonStream;
的AutoResetEvent commonLock;

无效监制()
{
  而(真)
  {
    magic.BlockUntilMagicAvalible();
    byte []的缓冲区= magic.Produce();
    commonStream.Write(缓冲液);
    commonLock.Set();
  }
}

无效消费()
{
  而(真)
  {
    commonLock.WaitOne();
    MagicalObject O = binarySerializer.Deserialize(commonStream);
    DoSomething的(O);
  }
}
 
多线程基础 02.线程间的通信与线程安全问题

解决方案

我会读下面的文章,他们描述你的问题。基本上你没有得到正确的隔离你的工作单位。

http://blogs.msdn.com/ B /瑞康/存档/ 2006/04/24 / 582643.aspx http://blogs.msdn.com/b/ricom/archive/2006/04/26/584802.aspx

hello i want to threads to collaborate a producer and a consumer. the consumer is rather slow, and the producer is very fast and works in bursts.

for example the consumer can process one message per 20 seconds, and the producer can produce 10 messages in one second, but does it about once in a long while so the consumer can catch up.

i want something like:

Stream commonStream;
AutoResetEvent commonLock;

void Producer()
{
  while (true)
  {
    magic.BlockUntilMagicAvalible();
    byte[] buffer = magic.Produce();
    commonStream.Write(buffer);
    commonLock.Set();
  }
}

void Consumer()
{
  while(true)
  { 
    commonLock.WaitOne();
    MagicalObject o = binarySerializer.Deserialize(commonStream);
    DoSomething(o);
  }
}

解决方案

I would read the following articles they describe your problem. Basically you're not getting the right isolation for your unit of work.

http://blogs.msdn.com/b/ricom/archive/2006/04/24/582643.aspx http://blogs.msdn.com/b/ricom/archive/2006/04/26/584802.aspx