建议22:确保集合的线程安全集合线程安全是指多个线程上添加或删除元素时,线程键必须保持同步。下面代码模拟了一个线程在迭代过程中,另一个线程对元素进行了删除。 class Program { static List<Person> list = new Lis ...
建议22:确保集合的get='_blank'>线程安全
集合线程安全是指多个线程上添加或删除元素时,线程键必须保持同步。
下面代码模拟了一个线程在迭代过程中,另一个线程对元素进行了删除。
class Program { static List<Person> list = new List<Person>() { new Person() { Name = "Rose", Age = 19 }, new Person() { Name = "Steve", Age = 45 }, new Person() { Name = "Jessica", Age = 20 }, }; static AutoResetEvent autoSet = new AutoResetEvent(false); static void Main(string[] args) { Thread t1 = new Thread(() => { //确保等待t2开始之后才运行下面的代码 autoSet.WaitOne(); foreach (var item in list) { Console.WriteLine("t1:" + item.Name); Thread.Sleep(1000); } }); t1.Start(); Thread t2 = new Thread(() => { //通知t1可以执行代码 autoSet.Set(); //沉睡1秒是为了确保删除操作在t1的迭代过程中 Thread.Sleep(1000); list.RemoveAt(2); }); t2.Start(); } } class Person { public string Name { get; set; } public int Age { get; set; } }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:编写高质量代码改善C#程序的157个建议——建议22:确保集合的线程安全
关键词:C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。