×
Login Register an account
Top Submissions Explore Upgoat Search Random Subverse Random Post Colorize! Site Rules
0

A better C# producer/consumer using delegates and events.

submitted by AugustineOfHippo2 to programming 2 yearsMay 11, 2022 11:46:19 ago (+1/-1)     (programming)

using System;

namespace EventDelegates
{
public delegate void DelItemProduced(int item);

public class producer{
public event DelItemProduced onItemProduced;

public void produceItem(){
Random r = new Random();
for (int i = 0; i < 10; i++){
onItemProduced( r.Next(1,10) );
System.Threading.Thread.Sleep(1000);//wait
}
}
}//end class producer
public class consumer{
public void consumeItem(int item){
Console.WriteLine("item produced: " + item);
}
}//end class consumer
class Program {
static void Main(string[] args)
{
producer p1 = new producer();
consumer c1 = new consumer();

p1.onItemProduced += new DelItemProduced(c1.consumeItem);
p1.produceItem();
}
}//end class program
}



2 comments block


[ - ] v0atmage 0 points 2 yearsMay 11, 2022 11:55:16 ago (+0/-0)

It's bad practice to create RNG instances on the fly. Every time produce item is invoked the seed gets reset.

[ - ] AugustineOfHippo2 [op] 0 points 2 yearsMay 11, 2022 12:35:32 ago (+0/-0)

Good point. It's just a learning exercise, and I thought generating random numbers was a fun way to simulate actually doing something.