I have a class with 2 queues - a and b.
When I insert values to the second queue(queue b) all values from the first one(queue a) are being removed.
Here is part of the class:
class SuperMarket
{
private Queue<string> a;
private Queue<string> b;
public SuperMarket()
{
this.a = new Queue<string>();
this.b = new Queue<string>();
}
public void InsertToA(string name)
{
this.a.Insert(name);
}
public void InsertToB(string name)
{
this.b.Insert(name);
}
this is the main program:
public static void Main(string[] args)
{
SuperMarket a = new SuperMarket();
Console.WriteLine("Enter Names For first");
string name = Console.ReadLine();
while (name.CompareTo("aaa") != 0)
{
a.InsertToA(name);
name = Console.ReadLine();
}
Console.WriteLine("Enter Names For second");
name = Console.ReadLine();
while (name.CompareTo("aaa") != 0)
{
a.InsertToB(name);
name = Console.ReadLine();
}
}
What might cause this effect?
Thank you very much!
After a few years later, I can easily answer my own question:
public void InsertToA(string name)
{
this.a.Enqueue(name);
}
public void InsertToB(string name)
{
this.b.Enqueue(name);
}
--> One should use Enqueue instead of Insert when working with generics in c#.
Related
I am a beginner in C# right now and my task is to write in console all the details of a product. I have to use the struct. I made a Product struct.
The function writeProducts cannot see the prod1 and all of its details.
However I get an error CS0103 that the name doesn't exist in current context and I don't know where I made a mistake.
Sorry, English is not my native language.
namespace project
{
class Program
{
public struct Product
{
public string Name;
public string Type;
public double Pr1pc;
public double Pr1kg;
public int number;
}
static void Main(string[] args)
{
Console.Clear();
Product prod1;
//Prod1
prod1.Name = "Chlyb";
prod1.Type = "szt";
prod1.Pr1pc = 6.30;
prod1.number = 1;
writeProducts();
Console.ReadKey();
Main(args);
}
static void writeProducts()
{
Console.WriteLine("{0}. {0},{0}{0}", prod1.number, prod1.Name, prod1.Pr1pc, prod1.Type);
}
}
}
You declared the variable prod1 in the Main function, so it is not recognized in the writeProducts function. Try to send the prod1 as a parameter to writeProducts like that:
class Program
{
public struct Product
{
public string Name;
public string Type;
public double Pr1pc;
public double Pr1kg;
public int number;
}
static void Main(string[] args)
{
Console.Clear();
Product prod1 = new();
//Prod1
prod1.Name = "Chlyb";
prod1.Type = "szt";
prod1.Pr1pc = 6.30;
prod1.number = 1;
writeProducts(prod1);
Console.ReadKey();
Main(args);
}
static void writeProducts(Product prod)
{
Console.WriteLine("{0}. {0},{0}{0}", prod.number, prod.Name, prod.Pr1pc, prod.Type);
}
}
}
Also notice you need to use the new word when declaring prod1
I am receiving an error: There is no argument given that corresponds to the required formal parameter 'x' of ReadingMaterial.By(string). I'm looking for a little guidance as to why there is an error. Is my syntax wrong, or is there something else I'm missing? I have been trying to learn C# by using some online tutorials and trying to change them up a bit.
namespace ReadingMaterials
{
class Presentation
{
static void Main(string[] args)
{
aForm Form = new aForm(); // available in hardcopy form aForm.availForm
Online O = new Online(); // amtBlogs, amtBooks
Book B = new Book(); // hardCover, softCover
Magazine M = new Magazine(); // numArticles
O.blog(5); //contains 5 blogs
O.oBook(3); //contains 3 online books
O.By("Beck"); //Written by Beck
O.words(678); //with 678 combined words
O.pics(1); // with one pic
Console.WriteLine("The auther {0} ", O.By());
Form.availForm();
B.hardCover(10); //10 hardcover books
B.softCover(2); //2 softcover books
B.By("Bruce"); //Writen by Bruce
B.words(188264); //words combined
B.pics(15); //15 pictures
Form.availForm();
M.articles(5); //5 articles
M.By("Manddi"); //Writen by Manddi
M.words(18064);//combined words
M.pics(81); //81 pictures
Form.availForm();
}
}
class ReadingMaterial
{
protected int amtWords;
string author;
protected int pic;
public void words(int w)
{
amtWords = w;
}
public void By(string x)
{
author = x;
}
public void pics(int pi)
{
pic = pi;
}
}
class Online : ReadingMaterial
{
int amtBlogs;
int amtBooks;
public void blog(int s)
{
amtBlogs = s;
}
public void oBook(int b)
{
amtBooks = b;
}
}
class Book : ReadingMaterial
{
int hard;
int soft;
public void hardCover(int h)
{
hard = h;
}
public void softCover(int s)
{
soft = s;
}
}
class Magazine:ReadingMaterial
{
int numArticles;
public void articles(int a)
{
numArticles = a;
}
}
interface IPrintable
{
void availForm();
}
class aForm : IPrintable
{
public void availForm ()
{
Console.WriteLine("Available in hard copy form!");
}
}
}
Console.WriteLine("The auther {0} ", O.By()); is the culprit. O.By() expects a string, and the By() function sets the author, but doesn't return any string. Since you've set the author using the By() function, you can make the author a public field, and do Console.WriteLine("The auther {0} ", O.author);
The problem is that you are calling By without any parameters in this line:
Console.WriteLine("The auther {0} ", O.By());
You can add a method to get the value instead:
class ReadingMaterial
{
...
public string GetBy()
{
return author;
}
....
}
Anyways, you might want to use properties instead of functions. You can look at the code working in here
class ReadingMaterial
{
public string Author {get;set;}
...
}
static void Main(string[] args)
{
...
O.Author = "Beck"; //Written by Beck
...
Console.WriteLine("The auther {0} ", O.Author);
}
You have defined the By method like this, with a parameter:
public void By(string x)
{
author = x;
}
But you are trying to call it without a parameter:
Console.WriteLine("The auther {0} ", O.By()); // not passing a parameter to 'By()'
If you want to access the author value of ReadingMaterial here then I would suggest making it a public property rather than a private field:
class ReadingMaterial
{
protected int amtWords;
public string Author { get; private set;}
// skipped
public void By(string x)
{
Author = x;
}
All of which kinds of begs the question - why use methods to set the values at all? Why not just use properties, as suggested below by #CarlosGarcia?
Please take note that this is uncompleted code, but just facing some small issue, as i using a lot of c++ OOP concept. i might have some issue when trying to change from another platform.
I get error when compiled and stated nonstatic method/property error
using System;
public class People
{
string name;
int age;
int height;
public virtual void insertDetail(People stu)
{
Console.Write("Please enter name : ");
stu.name = Console.ReadLine();
Console.Write("Please enter age : ");
while(!int.TryParse(Console.ReadLine(), out stu.age))
{
Console.WriteLine("You enter characters! Please re-insert");
}
Console.Write("Please enter height: ");
while(!int.TryParse(Console.ReadLine(), out stu.height))
{
Console.WriteLine("You enter characters! Please re-insert");
}
}
}
public class Class : People
{
static People[] students = new People[5];
public override void insertDetail(People stu)
{
Console.WriteLine("==================================");
base.insertDetail(stu);
}
public static void Main(string[] args)
{
for (int i = 0; i < students.Length; i++)
{
students[i] = new People();
insertDetail(students[i]);
}
Console.ReadKey();
}
}
As said in comments, you need an instance to use instance method.
Create an instance for Class inside Main
public class Class : People
{
static People[] students = new People[5];
public override void insertDetail(People stu)
{
Console.WriteLine("==================================");
base.insertDetail(stu);
}
public static void Main(string[] args)
{
Class c = new Class(); // this is required to access insertDetail
for (int i = 0; i < students.Length; i++)
{
students[i] = new People();
c.insertDetail(students[i]);
}
Console.ReadKey();
}
}
Check this Demo
You get that error when you make a static call to an instance method like Object.ToString() using the type name as the qualifier when you really need an instance.
First of all never use Class as your class name.
As for the error you need to give more information about what are you trying to do. You have to add static modifier to your method:
public static void insertDetail(People stu)
Or if you want for it to be override than:
public virtual void insertDetail()
{
this.name = "Some name";
//...
}
I am looking to access a list from different methods in the same class.Is there an easier way to access the movieTitle list without making a new list for each method? Do I have to make a reference to the list in every method? or should I put them all into a separate class all together? My overall goal is to have a option menu that gets input from the user and depending on the input calls a method to list all movies, add a movie to the list, and pick a random movie from the list.
class Program
{
static void Main(string[] args)
{
optionMenu();
Console.Read();
}
static void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "b") { randomPickMovie(); }
else { optionMenu(); }
}
static void printNames()
{
List<string> movieTitles = new List<string>();
/*list.....
/ movieTitles.Add("Jurassic Park");
/..........
/..........
*/..........
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
//I can't say...
//movieTitles.Add(newTitle);
//...? do I need to make an instance of the list?
}
static void randomPickMovie()
{
Random r = new Random();
int random = r.Next();
Console.WriteLine(movieTitle[random]);
//same here. How do I access the movie titles in the printName() method so
//I can randomly pick a movie from the list?
}
}
Below is one way make the movie list shared. This declares and initializes the list as a static member of the class (instead of a local variable in the methods).
This approach works well for simple programs, but having global state in a large program can be problematic because it becomes difficult to see which methods affect which global state so bugs can easily creep in. See below for another approach.
class Program
{
static void Main(string[] args)
{
...
}
static List<string> movieTitles = new List<string>();
static void optionMenu()
{
...
}
static void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
movieTitles.Add(newTitle);
}
static void randomPickMovie()
{
...
}
}
Another approach is to pass the data from one method to another. This makes it more obvious to see what methods use the movieList. It also allows us to specify additional restrictions, e.g. you can see that printNames only needs a read-only version of the list so you know that printNames can't modify the list. This approach is a little more work but it's a good habit to get into because it reduces bugs in the long term.
class Program
{
static void Main(string[] args)
{
...
}
static void optionMenu()
{
List<string> movieTitles = new List<string>();
string ui = Console.ReadLine();
if (ui == "a") { printNames(movieTitles); }
else if (ui == "b") { addMovie(movieTitles); }
else if (ui == "b") { randomPickMovie(movieTitles); }
else { optionMenu(); }
}
static void printNames(IReadOnlyList<string> movieTitles)
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie(List<string> movieTitles)
{
movieTitles.Add(newTitle);
}
static void randomPickMovie(List<string> movieTitles)
{
...
}
}
See https://stackoverflow.com/questions/13295319/instance-field-vs-passing-method-parameter for another user's point of view on which approach is better.
as for me, I prefer doing it this way.
class Program
{
static void Main(string[] args)
{
Movie movie = new Movie();
int x = 0;
while (x < 1)
{
movie.optionMenu(); Console.Write("Do you want to exit?");
string response = Console.ReadLine();
if (response == "Y") { x = 1; }
}
Console.Read();
}
}
class Movie
{
public List<string> movieTitles { get; set; }
public Movie()
{
movieTitles = new List<string>();
}
public void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "c") { randomPickMovie(); }
else { optionMenu(); }
}
public void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count; i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
public void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
if (newTitle != "")
{
movieTitles.Add(newTitle);
Console.WriteLine("New movie successfully added!");
}
else
{
Console.WriteLine("Cannot add empty movie. Add movie failed.");
}
}
public void randomPickMovie()
{
if (movieTitles.Count != 0)
{
Random r = new Random();
int random = r.Next(0, movieTitles.Count - 1);
Console.WriteLine(movieTitles[random]);
}
else { Console.WriteLine("Movie list is empty."); }
}
}
Answer for all your questions is create MovieTitles property of type List<string> and access it like this:
class Program
{
static void Main(string[] args)
{
optionMenu();
Console.Read();
}
static List<string> movieTitles;
static List<string> MovieTitles
{
get
{
if (movieTitles == null)
CreateMoviesList();
return movieTitles;
}
}
static void CreateMoviesList()
{
movieTitles = new List<string>();
/*list.....
/ movieTitles.Add("Jurassic Park");
/..........
/..........
*/
}
static void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "b") { randomPickMovie(); }
else { optionMenu(); }
}
static void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < MovieTitles.Count; i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
MovieTitles.Add(newTitle);
}
static void randomPickMovie()
{
Random r = new Random();
int random = r.Next();
Console.WriteLine(MovieTitles[random]);
}
}
CreateMoviesList() create list of movies only once and can be use to print movies, randon pick and add movies later on.
Inside my application I have list of persons from my database.
For every person I must call 5 (for now) services to search for some informations.
If service returns info I' adding it to that person (list of orders for specific person)
Because services work independent I thought I could try to run them parallel.
I've created my code as so:
using System;
using System.Collections.Generic;
using System.Threading;
namespace Testy
{
internal class Program
{
internal class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<string> Orders { get; private set; }
public Person()
{
// thanks for tip #juharr
Orders = new List<string>();
}
public void AddOrder(string order)
{
lock (Orders) //access across threads
{
Orders.Add(order);
}
}
}
internal class Service
{
public int Id { get; private set; }
public Service(int id)
{
Id = id;
}
//I get error when I use IList instead of List
public void Search(ref List<Person> list)
{
foreach (Person p in list)
{
lock (p) //should I lock Person here? and like this???
{
Search(p);
}
}
}
private void Search(Person p)
{
Thread.Sleep(50);
p.AddOrder(string.Format("test order from {0,2}",
Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(100);
}
}
private static void Main()
{
//here I load my services from external dll's
var services = new List<Service>();
for (int i = 1; i <= 5; i++)
{
services.Add(new Service(i));
}
//sample data load from db
var persons = new List<Person>();
for (int i = 1; i <= 10; i++)
{
persons.Add(
new Person {Id = i,
Name = string.Format("Test {0}", i)});
}
Console.WriteLine("Number of services: {0}", services.Count);
Console.WriteLine("Number of persons: {0}", persons.Count);
ManualResetEvent resetEvent = new ManualResetEvent(false);
int toProcess = services.Count;
foreach (Service service in services)
{
new Thread(() =>
{
service.Search(ref persons);
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
}
).Start();
}
// Wait for workers.
resetEvent.WaitOne();
foreach (Person p in persons)
{
Console.WriteLine("{0,2} Person name: {1}",p.Id,p.Name);
if (null != p.Orders)
{
Console.WriteLine(" Orders:");
foreach (string order in p.Orders)
{
Console.WriteLine(" Order: {0}", order);
}
}
else
{
Console.WriteLine(" No orders!");
}
}
Console.ReadLine();
}
}
}
I have 2 problems with my code:
When I run my app I should get list of 10 persons and for every person 5 orders, but from time to time (ones for 3-5 runs) for first person I get only 4 orders. How I can prevent such behaviour? solved! thanks to #juharr
How can I report progress from my threads? What I would like to get is one Function from my Program class that will be called every time order is added from service - I need that to show some kind of progress for every report. I was trying solution described here: https://stackoverflow.com/a/3874184/965722, but I'm wondering if there is an easier way. Ideally I would like to add delegate to Service class and place all Thread code there.
How should I add event and delegate to Service class and how to subscribe to it in Main method?
I'm using .NET 3.5
I've added this code to be able to get progress reports:
using System;
using System.Collections.Generic;
using System.Threading;
namespace Testy
{
internal class Program
{
public class ServiceEventArgs : EventArgs
{
public ServiceEventArgs(int sId, int progress)
{
SId = sId;
Progress = progress;
}
public int SId { get; private set; }
public int Progress { get; private set; }
}
internal class Person
{
private static readonly object ordersLock = new object();
public int Id { get; set; }
public string Name { get; set; }
public List<string> Orders { get; private set; }
public Person()
{
Orders = new List<string>();
}
public void AddOrder(string order)
{
lock (ordersLock) //access across threads
{
Orders.Add(order);
}
}
}
internal class Service
{
public event EventHandler<ServiceEventArgs> ReportProgress;
public int Id { get; private set; }
public string Name { get; private set; }
private int counter;
public Service(int id, string name)
{
Id = id;
Name = name;
}
public void Search(List<Person> list) //I get error when I use IList instead of List
{
counter = 0;
foreach (Person p in list)
{
counter++;
Search(p);
Thread.Sleep(3000);
}
}
private void Search(Person p)
{
p.AddOrder(string.Format("Order from {0,2}", Thread.CurrentThread.ManagedThreadId));
EventHandler<ServiceEventArgs> handler = ReportProgress;
if (handler != null)
{
var e = new ServiceEventArgs(Id, counter);
handler(this, e);
}
}
}
private static void Main()
{
const int count = 5;
var services = new List<Service>();
for (int i = 1; i <= count; i++)
{
services.Add(new Service(i, "Service " + i));
}
var persons = new List<Person>();
for (int i = 1; i <= 10; i++)
{
persons.Add(new Person {Id = i, Name = string.Format("Test {0}", i)});
}
Console.WriteLine("Number of services: {0}", services.Count);
Console.WriteLine("Number of persons: {0}", persons.Count);
Console.WriteLine("Press ENTER to start...");
Console.ReadLine();
ManualResetEvent resetEvent = new ManualResetEvent(false);
int toProcess = services.Count;
foreach (Service service in services)
{
new Thread(() =>
{
service.ReportProgress += service_ReportProgress;
service.Search(persons);
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
}
).Start();
}
// Wait for workers.
resetEvent.WaitOne();
foreach (Person p in persons)
{
if (p.Orders.Count != count)
Console.WriteLine("{0,2} Person name: {1}, orders: {2}", p.Id, p.Name, p.Orders.Count);
}
Console.WriteLine("END :)");
Console.ReadLine();
}
private static void service_ReportProgress(object sender, ServiceEventArgs e)
{
Console.CursorLeft = 0;
Console.CursorTop = e.SId;
Console.WriteLine("Id: {0,2}, Name: {1,2} - Progress: {2,2}", e.SId, ((Service) sender).Name, e.Progress);
}
}
}
I've added custom EventArgs, event for Service class.
In this configuration I should have 5 services running, but only 3 of them report progress.
I imagined that if I have 5 services I should have 5 events (5 lines showing progress).
This is probably because of threads, but I have no ideas how to solve this.
Sample output now looks like this:
Number of services: 5
Number of persons: 10
Press ENTER to start...
Id: 3, Name: Service 3 - Progress: 10
Id: 4, Name: Service 4 - Progress: 10
Id: 5, Name: Service 5 - Progress: 19
END :)
It should look like this:
Number of services: 5
Number of persons: 10
Press ENTER to start...
Id: 1, Name: Service 1 - Progress: 10
Id: 2, Name: Service 2 - Progress: 10
Id: 3, Name: Service 3 - Progress: 10
Id: 4, Name: Service 4 - Progress: 10
Id: 5, Name: Service 5 - Progress: 10
END :)
Last edit
I've moved all my thread creation to separate class ServiceManager now my code looks like so:
using System;
using System.Collections.Generic;
using System.Threading;
namespace Testy
{
internal class Program
{
public class ServiceEventArgs : EventArgs
{
public ServiceEventArgs(int sId, int progress)
{
SId = sId;
Progress = progress;
}
public int SId { get; private set; } // service id
public int Progress { get; private set; }
}
internal class Person
{
private static readonly object ordersLock = new object();
public int Id { get; set; }
public string Name { get; set; }
public List<string> Orders { get; private set; }
public Person()
{
Orders = new List<string>();
}
public void AddOrder(string order)
{
lock (ordersLock) //access across threads
{
Orders.Add(order);
}
}
}
internal class Service
{
public event EventHandler<ServiceEventArgs> ReportProgress;
public int Id { get; private set; }
public string Name { get; private set; }
public Service(int id, string name)
{
Id = id;
Name = name;
}
public void Search(List<Person> list)
{
int counter = 0;
foreach (Person p in list)
{
counter++;
Search(p);
var e = new ServiceEventArgs(Id, counter);
OnReportProgress(e);
}
}
private void Search(Person p)
{
p.AddOrder(string.Format("Order from {0,2}", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(50*Id);
}
protected virtual void OnReportProgress(ServiceEventArgs e)
{
var handler = ReportProgress;
if (handler != null)
{
handler(this, e);
}
}
}
internal static class ServiceManager
{
private static IList<Service> _services;
public static IList<Service> Services
{
get
{
if (null == _services)
Reload();
return _services;
}
}
public static void RunAll(List<Person> persons)
{
ManualResetEvent resetEvent = new ManualResetEvent(false);
int toProcess = _services.Count;
foreach (Service service in _services)
{
var local = service;
local.ReportProgress += ServiceReportProgress;
new Thread(() =>
{
local.Search(persons);
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
}
).Start();
}
// Wait for workers.
resetEvent.WaitOne();
}
private static readonly object consoleLock = new object();
private static void ServiceReportProgress(object sender, ServiceEventArgs e)
{
lock (consoleLock)
{
Console.CursorTop = 1 + (e.SId - 1)*2;
int progress = (100*e.Progress)/100;
RenderConsoleProgress(progress, '■', ConsoleColor.Cyan, String.Format("{0} - {1,3}%", ((Service) sender).Name, progress));
}
}
private static void ConsoleMessage(string message)
{
Console.CursorLeft = 0;
int maxCharacterWidth = Console.WindowWidth - 1;
if (message.Length > maxCharacterWidth)
{
message = message.Substring(0, maxCharacterWidth - 3) + "...";
}
message = message + new string(' ', maxCharacterWidth - message.Length);
Console.Write(message);
}
private static void RenderConsoleProgress(int percentage, char progressBarCharacter,
ConsoleColor color, string message)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.CursorLeft = 0;
int width = Console.WindowWidth - 1;
var newWidth = (int) ((width*percentage)/100d);
string progBar = new string(progressBarCharacter, newWidth) + new string(' ', width - newWidth);
Console.Write(progBar);
if (!String.IsNullOrEmpty(message))
{
Console.CursorTop++;
ConsoleMessage(message);
Console.CursorTop--;
}
Console.ForegroundColor = originalColor;
}
private static void Reload()
{
if (null == _services)
_services = new List<Service>();
else
_services.Clear();
for (int i = 1; i <= 5; i++)
{
_services.Add(new Service(i, "Service " + i));
}
}
}
private static void Main()
{
var services = ServiceManager.Services;
int count = services.Count;
var persons = new List<Person>();
for (int i = 1; i <= 100; i++)
{
persons.Add(new Person {Id = i, Name = string.Format("Test {0}", i)});
}
Console.WriteLine("Services: {0}, Persons: {1}", services.Count, persons.Count);
Console.WriteLine("Press ENTER to start...");
Console.ReadLine();
Console.Clear();
Console.CursorVisible = false;
ServiceManager.RunAll(persons);
foreach (Person p in persons)
{
if (p.Orders.Count != count)
Console.WriteLine("{0,2} Person name: {1}, orders: {2}", p.Id, p.Name, p.Orders.Count);
}
Console.CursorTop = 12;
Console.CursorLeft = 0;
Console.WriteLine("END :)");
Console.CursorVisible = true;
Console.ReadLine();
}
}
}
Basically you have a race condition with the create of the Orders. Imagine the following execution of two threads.
Thread 1 checks if Orders is null and it is.
Thread 2 checks if Orders is null and it is.
Thread 1 sets Orders to a new list.
Thread 1 gets the lock.
Thread 1 adds to the Orders list.
Thread 2 sets Order to a new list. (you just lost what Thread 1 added)
You need to include the creation of the Orders inside the lock.
public void AddOrder(string order)
{
lock (Orders) //access across threads
{
if (null == Orders)
Orders = new List<string>();
Orders.Add(order);
}
}
Or you really should create the Order list in a Person constructor
public Person()
{
Orders = new List<Order>();
}
Also you should really create a separate object for locking.
private object ordersLock = new object();
public void AddOrder(string order)
{
lock (ordersLock) //access across threads
{
Orders.Add(order);
}
}
EDIT:
In your foreach where you create the threads you need to create a local copy of the service to use inside the lambda expression. This is because the foreach will update the service variable and the thread can end up capturing the wrong variable. So something like this.
foreach (Service service in services)
{
Service local = service;
local.ReportProgress += service_ReportProgress;
new Thread(() =>
{
local.Search(persons);
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
}
).Start();
}
Note the subscription doesn't need to be inside the thread.
Alternatively you could move the creation of the thread inside the Search method of your Service class.
Additionally you might want to create a OnReportProgress method in the Service class like so:
protected virtual void OnReportProgress(ServiceEventArgs e)
{
EventHandler<ServiceEventArgs> handler = ReportProgress;
if (handler != null)
{
handler(this, e);
}
}
Then call that inside your Search method. Personally I'd call it in the public Search method and make the counter a local variable as well to allow for reuse of the Service object on another list.
Finally you will need an additional lock in the event handler when writing to the console to make sure one thread doesn't change the cursor position before another one writes it's output.
private static object consoleLock = new object();
private static void service_ReportProgress(object sender, ServiceEventArgs e)
{
lock (consoleLock)
{
Console.CursorLeft = 0;
Console.CursorTop = e.SId;
Console.WriteLine("Id: {0}, Name: {1} - Progress: {2}", e.SId, ((Service)sender).Name, e.Progress);
}
}
Also you might want to use Console.Clear() in the following locaiton:
...
Console.WriteLine("Number of services: {0}", services.Count);
Console.WriteLine("Number of persons: {0}", persons.Count);
Console.WriteLine("Press ENTER to start...");
Console.Clear();
Console.ReadLine();
...
And you'll need to update the cursor position before your write out your end statement.
Console.CursorTop = 6;
Console.WriteLine("END :)");
This might not totally answer your question (but I think you might have a race condition), when you start dealing with threads you need to implement proper synchronization when updating objects from different threads. You should make sure only one thread is able to update an instance of the person class at any given time.
The p.AddOrder( should have mutex that ensures only one thread is updating the Person object.