C# for和foreach解析

    xiaoxiao2021-03-29  26

    首先上一部分代码:

    private static List<AllShop> allShop = new List<AllShop>();//临时存放推送商场 public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { writestr("服务启动"); timer1.Enabled = true; timer1.Interval = basetime; get_Shops(); for (int i = 0; i < allShop.Count; i++) { //为每个shop开启新线程 ThreadStart threadStart = new ThreadStart(delegate () { try { pushDDXX(allShop[i]); writestr(allShop[i].getShopID() + "线程结束"); } catch (Exception ex) { writestr("OnStart_"+ i + ":"+ex.Message.ToString()); } }); Thread thread = new Thread(threadStart); thread.Start(); } } 看出有什么问题了吗?

    这是报错日志:

    2017-04-13 09:46:30 OnStart_16:索引超出范围。必须为非负值并小于集合大小。

    这里的

    allShop.Count是等于16的。所以理论上不会出现上述问题,不可能索引超出范围。

    这是更改后的:

    private static List<AllShop> allShop = new List<AllShop>();//临时存放推送商场 public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { writestr("服务启动"); timer1.Enabled = true; timer1.Interval = basetime; get_Shops(); foreach (var shop in allShop) { //为每个shop开启新线程 ThreadStart threadStart = new ThreadStart(delegate () { try { pushDDXX(shop); writestr(shop.getShopID() + "线程结束"); } catch (Exception ex) { writestr("OnStart_"+ shop.getShopID() + ":"+ex.Message.ToString()); } }); Thread thread = new Thread(threadStart); thread.Start(); } }

    后来经过断点调试,发现在多线程中,for循环的i+1后,前面代码里的i也会跟着改变。for循环停止的时候i=16,这时候不管在哪个线程,只要没有走完i都是16。外层循环结束的时候,里面的执行方法不一定结束了。 这个错误在于没有理解for循环和进程的关系,以为最后i=16的时候不会走进去,其实这是个误区,i=16的时候只是不再产生新的进程,但所有进程都使用一个全局的i,所以最终出现了writestr(allShop[i].getShopID() + "线程结束");导致错误,改法就是把变量作为参数传进去。

    或者 用ParameterizedThreadStart委托代替ThreadStart委托并在匿名委托方法体中用委托参数代替i用thread[i].Start(i)来启动线程

    转载请注明原文地址: https://ju.6miu.com/read-664863.html

    最新回复(0)