c# 依电脑线程数,开启并行计算
时间: 2023-07-18 20:11:03 浏览: 51
在C#中,可以使用Parallel类来实现并行计算。该类提供了一系列静态方法,可以让我们很方便地进行并行计算。
要根据电脑线程数来开启并行计算,可以使用Environment类的ProcessorCount属性来获取当前电脑的线程数。然后,将获取到的线程数作为Parallel类的第二个参数传入即可。
下面是一个示例代码:
```
int threadCount = Environment.ProcessorCount;
Parallel.For(0, data.Length, new ParallelOptions { MaxDegreeOfParallelism = threadCount }, i =>
{
// 进行并行计算的操作
});
```
在上面的代码中,我们首先获取了当前电脑的线程数,然后将其作为Parallel类的MaxDegreeOfParallelism属性的值传入。这样,就可以让Parallel类根据电脑的线程数来开启并行计算了。
相关问题
c#多线程并行处理,通过task实现
这个问题中的“c”不是一个具体的问题或主题,因此我将根据我的理解给出一个大于300字的文章。
“c”是字母表中的第三个字母,它是一个辅音字母。在拼音中,它的发音为“cì”,它在汉语-拉丁字母拼音中的替代字母是“ch”。在英语中,单独的字母“c”可能是代表一些词汇的表示。
除了作为字母表中一个单独的字母代表“cì”这个词语的拼音外,它还有一些其他的含义和用途。例如,在数学中,“c”可能代表复变量,也可以表示常数。在计算机科学中,“c”是一种编程语言,并且“C++”是一个流行的编程语言,也是可以用于面向对象编程的一种编程语言。
另外,“C”也是一个介于B和D之间的字母,它一直被用来指代中间的一个选项。例如,在多项选择题中,它可以表示“无法确定”或“不适用”。而在评分尺度中,它可以代表“被判定为不合格”。
总之,字母“c”在我们的日常生活和实践中有着广泛的应用和含义。在不同的场景和学科领域中,它都扮演着不同的角色和意义。无论是作为一个字母、一个符号还是一个编程语言,我们都应该学习和了解它的定义和基础知识。
OpenCVSharp 并行计算Canny亚像素级别的匹配c#代码
下面是使用OpenCVSharp进行并行计算Canny边缘检测的C#代码:
```csharp
using System;
using System.Threading.Tasks;
using OpenCvSharp;
namespace ParallelCannyEdgeDetection
{
class Program
{
static void Main(string[] args)
{
Mat src = new Mat("input.jpg", ImreadModes.Color);
Mat dst = new Mat(src.Size(), MatType.CV_8UC1);
int height = src.Rows;
int width = src.Cols;
// Create an array to store the number of threads to use for each row
int[] numThreads = new int[height];
// Divide the image into rows and assign the number of threads based on the row's position
Parallel.For(0, height, y =>
{
// Determine the number of threads to use for this row based on its position
numThreads[y] = (int)(width * Math.Abs(Math.Sin(y / (double)height * Math.PI * 2.0)) / 4.0);
// Clamp the number of threads to be between 1 and the width of the image
numThreads[y] = Math.Min(numThreads[y], width);
numThreads[y] = Math.Max(numThreads[y], 1);
});
// Apply Canny edge detection to each row in parallel using the number of threads calculated above
Parallel.For(0, height, y =>
{
Mat row = new Mat(src, new Rect(0, y, width, 1));
Mat rowDst = new Mat(dst, new Rect(0, y, width, 1));
Cv2.Canny(row, rowDst, 50, 150);
// Apply sub-pixel edge detection to the output of the Canny algorithm
Cv2.FindContours(rowDst, out var contours, out _, RetrievalModes.List, ContourApproximationModes.ApproxTC89KCOS);
Cv2.DrawContours(rowDst, contours, -1, Scalar.White, 1, LineTypes.Link8);
// Release the temporary Mats created for this row
row.Dispose();
rowDst.Dispose();
});
Cv2.ImWrite("output.jpg", dst);
}
}
}
```
该代码使用`Parallel.For()`方法将图像分成行,并为每一行分配一个线程数,以便在每一行上并行应用Canny边缘检测算法。然后,它使用`FindContours()`方法和`DrawContours()`方法来在输出的二进制图像上进行亚像素级别的边缘检测。最后,它将结果保存到`output.jpg`文件中。