I want to simulate producer Consumer in C#.One thread works as producer,which new array objects,and put that array in List.Another thread works as comsumer,when there are elements in the List,it get the array and do something. Codes are here.Why there are "null"s in the process. How to fix it? The problem mybe caused by when calling list.add(tmp), list.Count is added one before the ushort[] tmp is ready.Can anyone explain the mechanism of such process.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace listTest
{
class Program
{
static List<ushort[]> list = new List<ushort[]>();
static void func1()
{
while (true)
{
ushort[] tmp;
while (true)
{
tmp = new ushort[100];
if (tmp != null)
break;
}
list.Add(tmp);
Thread.Sleep(10);
}
}
static void func2()
{
while (true)
{
if (list.Count > 0)
{
ushort[] data = list.ElementAt(0);
if (data == null)
Console.Write("null\n");
else
{
for (int i = 0; i < data.Length; i++)
{
data[i] += 1;
}
}
Console.Write("ok ");
list.RemoveAt(0);
}
}
}
static void Main(string[] args)
{
Thread func1T = new Thread(func1);
Thread func2T = new Thread(func2);
func1T.Start();
func2T.Start();
}
}
}