首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

多线程 同时读取一个集合 如何才能 只读取一遍

2013-06-19 
多线程同时读取一个集合怎么才能 只读取一遍public class demo{public int ID { get set }public string

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



    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);
                tf.StartNew(() => read(listdemo));
                tf.StartNew(() => read(listdemo));



            }
              );
 parent.Start();
            parent.Wait();
            Console.Read();
        }



C#??多线程??Task
[解决办法]
你可以参照双检锁实现的单例模式,原理类似,当然方法还有很多种

热点排行