繁体   English   中英

C#中的通用缓冲区[Java中的示例]

[英]Generic buffer in C# [example in Java]

在具有多个线程的消费者 - 生产者情况下,是否可以使用任何库类用于缓冲区? 我不太了解C#的多线程方式,所以完美解决方案的例子是Java:

//Thread 1
Buffer buf = new Buffer();
Thread t2 = new Thread(new MyRunnable(buf) );
    while(true){
        buf.put(foo);
    }
}

//MyRunnable
private Buffer buf;

public MyRunnable(Buffer buf){
    this.buf = buf;
}

public void run(){
    while(!buf.IsFinished()){
        foo = buf.take();
        dosth(foo);
    }
}

System.Collection.Concurrent有许多IProducerConsumerCollection<T>接口的实现(例如ConcurrentQueue<T> ),它们可能在您的情况下使用。

还有一个BlockingCollection<T>类,允许您的线程在等待输入时阻塞。

您可以使用.NET 4.0的ConcurrentBag<T> 它实现了IProducerConsumerCollection<T>设计的IProducerConsumerCollection<T>

如果订单很重要,您可以查看ConcurrentQueue<T>ConcurrentStack<T>

看起来你只是想找到一种方法在后台线程中做一些工作并将收集的数据传递给调用者?

您可以使用BackgroundWorker类。 它允许您创建一个简单的后台线程,并在完成后将某些内容传递给调用者。

public class TestClass
{
   private BackgroundWorker worker;

   public void DoSomeWorkAsync()
   {
      this.worker = new BackgroundWorker();
      this.worker.DoWork += this.OnDoWork;
      this.worker.RunWorkerCompleted += this.OnWorkerComplete;
      this.worker.RunWorkerAsync();
   }  

   private void OnDoWork(object sender, DoWorkEventArgs e)
   {
      //do long running process here to pass to calling thread.
      //note this will execute on a background thread
      DataTable DT = GetSomeData();
      e.Result = DT;
   }

   private void OnWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
   {
      //note this event is fired on calling thread
      if (e.Error != null)
         //do something with the error
      else if (e.Cancelled) 
         //handle a cancellation
      else
         //grab the result
         foo = e.Result;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM