簡體   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