C#线程间通信 [英] c# inter-thread communication

查看:142
本文介绍了C#线程间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想是这样的:

 流commonStream;
的AutoResetEvent commonLock;

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

无效消费()
{
  而(真)
  {
    commonLock.WaitOne();
    MagicalObject O = binarySerializer.Deserialize(commonStream);
    DoSomething的(O);
  }
}
 

解决方案

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

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

这篇关于C#线程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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