获取“异常".这段代码有什么问题? [英] Getting an 'Exception'. What is wrong in this code?

查看:57
本文介绍了获取“异常".这段代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该代码用于并行运行多行,但所有列均按顺序运行..

The code is for running multiple rows in parallel, but all the columns in sequence..

/*************ADDING two 2-d ARRAYS*********/

         int[,] c = new int[2,3];
         int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } };
         int[,] b = { { 1, 2, 3 }, { 4, 5, 6 } };

         int j;

         // Console.WriteLine(c.Length / 2);   To get the length of second dimention of an array.

         Parallel.For(0, c.Length / 2, (int i) =>
             {
                 for (j = 0; j < 3; j++)
                 {
                     c[i, j] = a[i, j] + b[i, j];
                     Console.WriteLine("c[" + i + "," + j + "] = " + c[i, j]);
                 }
             }
         );

推荐答案

这是设计使然,您的Parallel.For仅对行进行操作.

列由普通的for处理.
This is by design, your Parallel.For is operating on rows only.

The columns are processed by a normal for.


如果进行简单检查,原因很明显:
If you do a simple check, the reason is obvious:
int[,] c = new int[2,3];
Console.WriteLine(c.Length / 2);


打印"3".
这意味着i会在0到2之间变化-并超出范围...


Prints "3".
Which means that i will vary between 0 and 2 - and go out of range...


这篇关于获取“异常".这段代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆