日期:2014-05-17  浏览次数:20905 次

多线程 同时读取一个集合 怎么才能 只读取一遍


    public class demo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int State { get; set; }
        public string DownFrom { get; set; }
    }
 static List<demo> listdemo = new List<demo>();
   public static void add()
        {

            for (int i = 0; i < 100; i++)
            {
                demo dm = new demo { ID = i, Name = "Test" + i, DownFrom = "中国", State = 0 };
                listdemo.Add(dm);
                           
            }}
    public static void read(List<demo> listthread)
        {
           // lock (listthread)
           // {

            foreach (var dm in listthread)
            {
                Console.WriteLine(dm.ID + "\t" + dm.Name + "\t" + dm.DownFrom + "\t线程" + Task.CurrentId));
                Thread.Sleep(1000);
           // }
            }
        }
 static void Main(string[] args)
        {
    Task parent = new Task(() =>
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                var tf = new TaskFactory(cts.Token,
                TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
              tf.StartNew(() => read(list[0],(int)Task.CurrentId)).ContinueWith(TaskEnded);
          &