C#中的通用缓冲区[Java中的示例]
本文关键字:Java 缓冲区 | 更新日期: 2023-09-27 18:20:38
在有多个线程的消费者-生产者情况下,有什么库类可以用作缓冲区吗?我不太了解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>
。它实现了为此而设计的CCD_ 6。
如果订单很重要,您可以查看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;
}
}