Is there any library class I can use for a buffer in a consumer-producer situation with multiple threads? I don't very well understand the multithreading ways of C# so thew example of a perfect solution is in 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
has a number of implementations of the IProducerConsumerCollection<T>
interface (eg ConcurrentQueue<T>
), which may be of use in your situation.
There is also a BlockingCollection<T>
class that lets your thread block while waiting for the input.
You could use .NET 4.0's ConcurrentBag<T>
for this. It implements IProducerConsumerCollection<T>
which is designed for that.
If order matters, you can look at ConcurrentQueue<T>
or ConcurrentStack<T>
.
It looks like you're just trying to find a way to do some work in a background thread and pass collected data off to the caller?
You could use the BackgroundWorker class for this. It allows you to create a simple background thread and pass off something back to the caller when you're done.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.