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()

        {

            //該線程是期望創建一個共享列表的獨立鏡像,然后對鏡像進行費時的操作

            while (true)

            {

                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);

                }

 

            }

        }

    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM