如何将循环与return语句并行化?

时间:2012-11-12 15:43:55

标签: c# loops parallel-processing return

我有一个Bitmap扩展方法,它将在另一个Bitmap中搜索“this”Bitmap,如果找到它将返回找到它的Point。该算法通过逐行搜索较大图像的行来工作。我想将行分成与我的机器上有核心一样多的部分,并异步搜索它们。如果其中一个线程找到了图像,则需要取消其他线程。这可以通过并行实现吗?

public static Point LocateWithin(this Bitmap smaller, Bitmap larger) {

        if (smaller.Width > larger.Width || smaller.Height > larger.Height)
            return new Point(-1, -1);

        Rectangle smallerRectangle = new Rectangle(0, 0, smaller.Width, smaller.Height);
        Rectangle largerRectangle = new Rectangle(0, 0, larger.Width, larger.Height);

        BitmapData smallerData = smaller.LockBits(smallerRectangle,
                                                  ImageLockMode.ReadOnly,
                                                  PixelFormat.Format32bppRgb);
        BitmapData largerData = larger.LockBits(largerRectangle,
                                                ImageLockMode.ReadOnly,
                                                PixelFormat.Format32bppRgb);

        try {
            IntPtr largerPtr = largerData.Scan0;
            IntPtr smallerPtr = smallerData.Scan0;

            int smallerStrideLessOne = smallerData.Stride - 4;
            int smallerHeightLessOne = smaller.Height - 1;
            int heightDiff = larger.Height - smaller.Height;
            int widthDiff = larger.Width - smaller.Width;

            for (int yl = 0; yl <= heightDiff; yl++) {
                for (int xl = 0; xl <= widthDiff; xl++) {

                    if (memcmp(smallerPtr, largerPtr, smallerData.Stride) == 0) {

                        IntPtr lPtr = largerPtr;
                        IntPtr sPtr = smallerPtr;

                        bool isMatch = true;
                        for (int ys = 0; ys < smallerHeightLessOne; ys++) {
                            lPtr += largerData.Stride;
                            sPtr += smallerData.Stride;
                            if (memcmp(sPtr, lPtr, smallerData.Stride) != 0) {
                                isMatch = false;
                                break;
                            }
                        }
                        if (isMatch)
                            return new Point(xl, yl);
                    }
                    largerPtr += 4;
                }
                largerPtr += smallerStrideLessOne;
            }
        }
        finally {
            smaller.UnlockBits(smallerData);
            larger.UnlockBits(largerData);
        }
        return new Point(-1, -1);
    }

0 个答案:

没有答案