当前位置: 移动技术网 > IT编程>开发语言>c# > C#程序编写高质量代码改善的157个建议【20-22】[泛型集合、选择集合、集合的安全]

C#程序编写高质量代码改善的157个建议【20-22】[泛型集合、选择集合、集合的安全]

2019年12月10日  | 移动技术网IT编程  | 我要评论

 

建议20、使用泛型集合来替代非泛型集合

 这里有一篇文章,是我之前专门来介绍泛型的。我们应尽量的使用泛型集合。因为泛型的确有它的好处:

1、提供了类型安全,在编译期间就可以检查错误

2、更重要的是大部分情况下泛型集合的性能比非泛型集合的性能都高很多。

下面我们来看一段简单的测试性能的代码:

复制代码
class program
    {
        static int collectioncount = 0;
        static stopwatch watch = null;
        static int testcount = 10000000;
        static void testbegin()
        {
            gc.collect(); ////强制对所有代码进行即时垃圾回收
            gc.waitforpendingfinalizers();////挂起线程,执行终结器队列中的终结器(即析构方法)
            gc.collect();///再次对所有代码进行垃圾回收,主要包括从终结器队列中出来的对象
            collectioncount = gc.collectioncount(0);///返回在0代中执行的垃圾回收次数
            watch = new stopwatch();
            watch.start();
        }

        static void testend()
        {
            watch.stop();
            console.writeline("耗时:{0}",watch.elapsedmilliseconds.tostring());
            console.writeline("垃圾回收次数:{0}", gc.collectioncount(0) - collectioncount);
        }
        static void testarraylist()
        {
            arraylist arraylist = new arraylist();
            int temp = 0;
            for (int i = 0; i < testcount; i++)
            {
                arraylist.add(i);
                temp = (int)arraylist[i];
            }
            arraylist = null;
        }

        static void testgenericlist()
        {
            list<int> list = new list<int>();
            int temp = 0;
            for (int i = 0; i < testcount; i++)
            {
                list.add(i);
                temp = list[i];
            }
            list = null;
        }
        static void main(string[] args)
        {
            console.writeline("开始测试arraylist");
            testbegin();
            testarraylist();
            testend();
            console.writeline("开始测试list<t>");
            testbegin();
            testgenericlist();
            testend();
            console.readline();
        }
    }
复制代码

执行结果如下

   我上面测试的次数是10000000,可以发现,两者在垃圾回收次数和耗时都差距比较大,所以泛型集合有着非泛型集合无法超越的优势。所以还是尽量在我们的程序中使用泛型集合吧。

建议21、选择正确的集合

 这里有一篇我刚写的关于集合的博文,主要是简单介绍了一下关于自己使用比较频繁的几个集合。

如果集合的数目固定并且不涉及转型,使用数组效率高,否则就是使用list<t>。

像使用数组、arraylist、list<t>、dictionary<key,value>这些集合的有点就是插入和删除数据效率比较高,缺点就是查找的效率相对来说低一些。

关于队列可以参考

关于栈可以参考

建议22、确保集合的线性安全

   建议18中提到,foreach循环不能代替for循环的一个原因是在迭代过程中对集合本身进行了增删操作。将此场景移植到多线程场景中,就是本建议要阐述的重点:确保集合的线程安全。集合线程安全是指在多个线程上添加活删除元素时,线程之间必须保持同步。

  下面我们来通过实例来更详细的查看一下,先简单定义一个实体类

    public class person
    {
        public string name { get; set; }
        public int age { get; set; }
    }
复制代码
       static list<person> list = new list<person>() 
        { 
            new person(){ name="aehyok",age=25},
            new person(){name="kris",age=23},
            new person(){name="leo",age=26}
        };
        static autoresetevent autoset = new autoresetevent(false);
        static void main(string[] args)
        {
            thread t1 = new thread(() => 
            {
                ///阻止当前线程
                autoset.waitone();   
                foreach (var item in list)
                {
                    console.writeline("t1:"+item.name);
                    thread.sleep(1000);
                }
            });
            t1.start();

            thread t2 = new thread(() => 
            { 
                ///通知t1可以执行代码
                autoset.set();
                thread.sleep(1000);
                list.removeat(2);
            });
            t2.start();

            console.readline();
        }
复制代码

再来简单分析一下这段代码,其实就是闲定义了一个list集合,然后又定义了一个 autorestevent的实例,用于控制线程的。

接下来在main函数中定义了两个线程,在线程一中将线程一暂停,然后当调用线程二的时候再来通知线程一继续运行。最终运行结果

 

主要是因为线程一在暂停之后,开始运行线程二随即线程一得到通知可以继续运行,通过代码可以发现都有thread.sleep(1000);也就是为了保证两个线程都还在运行期间,线程二移除了集合中的一个元素,那么当线程一再次循环的时候,导致了错误的发生。

早在泛型集合出现之前,非泛型集合一般会提供一个syncroot属性,要保证非泛型集合的线程安全,可以通过锁定该属性来实现。如果上面的集合用arraylist代替,保证线程安全则应该在迭代和删除的时候都加上锁lock,代码如下所示:

复制代码
        static arraylist list = new arraylist() 
        { 
            new person(){ name="aehyok",age=25},
            new person(){name="kris",age=23},
            new person(){name="leo",age=26}
        };
        static autoresetevent autoset = new autoresetevent(false);
        static void main(string[] args)
        {
            thread t1 = new thread(() => 
            {
                ///阻止当前线程
                autoset.waitone();
                lock (list.syncroot)
                {
                    foreach (person item in list)
                    {
                        console.writeline("t1:" + item.name);
                        thread.sleep(1000);
                    }
                }

            });
            t1.start();

            thread t2 = new thread(() => 
            { 
                ///通知t1可以执行代码
                autoset.set();
                thread.sleep(1000);
                lock (list.syncroot)
                {
                    list.removeat(2);
                }
                
            });
            t2.start();

            console.readline();
        }
复制代码

运行结果就是线程一执行通过

如果你试过,那么会发现泛型集合没有这样的属性来进行加锁,必须要自己创建一个锁定对象来完成同步的任务。

所以第一个例子我们可以这样进行修改

复制代码
 static list<person> list = new list<person>() 
        { 
            new person(){ name="aehyok",age=25},
            new person(){name="kris",age=23},
            new person(){name="leo",age=26}
        };
        static object syncobject = new object();
        static autoresetevent autoset = new autoresetevent(false);
        static void main(string[] args)
        {
            thread t1 = new thread(() => 
            {
                ///阻止当前线程
                autoset.waitone();
                lock (syncobject)
                {
                    foreach (var item in list)
                    {
                        console.writeline("t1:" + item.name);
                        thread.sleep(1000);
                    }
                }
            });
            t1.start();
            thread t2 = new thread(() => 
            { 
                ///通知t1可以执行代码
                autoset.set();
                thread.sleep(1000);
                lock (syncobject)
                {
                    list.removeat(2);
                } 
            });
            t2.start();

            console.readline();
        }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网