現在,我正在學習C#中的多線程和使用它。所以,我面臨的問題如下: (對不起,我這麼簡單的問題)在C#中管理線程關係#
假設我們有兩個名爲Producer和Consumer的類。生產者任務正在生成4個數字,而程序運行和消費者任務正在消耗並使用這些數字,並在程序結束時返回它們的總和。
消費類定義:
class Consumer
{
private HoldInteger sharedLocation;
private Random randomSleepTime;
public Consumer(HoldInteger shared, Random random)
{
sharedLocation = shared;
randomSleepTime = random;
}
public void Consume()
{
int sum = 0;
for (int i = 1; i <= 4; i++)
{
Thread.Sleep(randomSleepTime.Next(1, 3000));
sum += sharedLocation.Buffer;
}
}
}
和製作類的定義如下:
class Producer
{
private HoldInteger sharedLocation;
private Random randomSleepTime;
public Producer(HoldInteger shared, Random random)
{
sharedLocation = shared;
randomSleepTime = random;
}
public void Produce()
{
for (int i = 1; i <= 4; i++)
{
Thread.Sleep(randomSleepTime.Next(1, 3000));
sharedLocation.Buffer = i;
}
}
}
而且,我們已經HoldInteger
類包含緩衝變量,生產者寫這個變量和消費者讀從那。我結合這些類和程序我的主要方法,下面的代碼:
static void Main(string[] args)
{
HoldInteger holdInteger = new HoldInteger();
Random random = new Random();
Producer producer = new Producer(holdInteger, random);
Consumer consumer = new Consumer(holdInteger, random);
Thread producerThread = new Thread(new ThreadStart(producer.Produce));
producerThread.Name = "producer";
Thread consumerThread = new Thread(new ThreadStart(consumer.Consume));
consumerThread.Name = "consumer";
producerThread.Start();
consumerThread.Start();
}
所以,我的問題是,How can i manage this relationship With Low Memory and Time Wasting ?
請注意,這些線程管理代碼將被放置在HoldInteger
類主體。
感謝您的關注。
非常感謝,這是非常有用的:) –
@Hossein,盡情享受吧! :) – Kiril