天天看點

C# 如何避免異常”集合已修改;可能無法執行枚舉操作。“

using System;

using System.Collections.Generic;

using System.Text;

using LogHandler;

using System.Threading;

namespace ConsoleApplication5

{

    class Program

    {

        private static List<string> lstShare = new List<string>();

        static void Main(string[] args)

        {

            Thread th1 = new Thread(thread1);

            th1.Start();

            Thread th2 = new Thread(thread2);

            th2.Start();

        }

        private static void thread1()

            //該線程不停地獨占清單,并追加資料

            while (true)

            {

                lock (lstShare)

                {

                    lstShare.Add("aaa");

                }

            }

        private static void thread2()

            //該線程是期望建立一個共享清單的獨立鏡像,然後對鏡像進行費時的操作

                try

                    List<string> lstTemp = new List<string>();

                    lock (lstShare)

                    {

                        lstTemp = lstShare;//如果使用這一句來建立鏡像,就會發生異常

                        #region "正确的做法"

                        //foreach (string item in lstShare)

                        //{

                        //    lstTemp.Add(item);

                        //}

                        #endregion

                    }

                    foreach (string item in lstTemp)

                        //do nothing

                        Thread.Sleep(1);

                catch (System.Exception ex)

                    Console.WriteLine(ex.Message);

    }

}