다음을 통해 공유


방법: PLINQ에서 병합 옵션 지정

업데이트: 2010년 5월

이 예제에서는 PLINQ 쿼리의 모든 후속 연산자에 적용할 병합 옵션을 지정하는 방법을 보여 줍니다. 병합 옵션을 명시적으로 설정할 필요는 없지만 이렇게 하면 성능이 향상될 수 있습니다. 병합 옵션에 대한 자세한 내용은 PLINQ의 병합 옵션을 참조하십시오.

주의 정보주의

이 예제는 사용법을 보여 주기 위한 것이며, 이에 상응하는 순차 LINQ to Objects 쿼리보다 실행 속도가 느릴 수 있습니다.속도 향상에 대한 자세한 내용은 PLINQ의 속도 향상 이해를 참조하십시오.

예제

다음 예제에서는 소스의 순서가 지정되지 않고 모든 요소에 부담이 큰 함수가 적용되는 기본적인 경우의 병합 옵션 동작을 보여 줍니다.

Class MergeOptions2


    Sub DoMergeOptions()

        Dim nums = Enumerable.Range(1, 10000)

        ' Replace NotBuffered with AutoBuffered 
        ' or FullyBuffered to compare behavior.
        Dim scanLines = From n In nums.AsParallel().WithMergeOptions(ParallelMergeOptions.NotBuffered)
              Where n Mod 2 = 0
              Select ExpensiveFunc(n)

        Dim sw = System.Diagnostics.Stopwatch.StartNew()
        For Each line In scanLines
            Console.WriteLine(line)
        Next

        Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.")
        Console.ReadKey()

    End Sub
    ' A function that demonstrates what a fly
    ' sees when it watches television :-)
    Function ExpensiveFunc(ByVal i As Integer) As String
        System.Threading.Thread.SpinWait(2000000)
        Return String.Format("{0} *****************************************", i)
    End Function
End Class
namespace MergeOptions
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;

    class Program
    {
        static void Main(string[] args)
        {

            var nums = Enumerable.Range(1, 10000);

            // Replace NotBuffered with AutoBuffered 
            // or FullyBuffered to compare behavior.
            var scanLines = from n in nums.AsParallel()
                                .WithMergeOptions(ParallelMergeOptions.NotBuffered)
                            where n % 2 == 0
                            select ExpensiveFunc(n);

            Stopwatch sw = Stopwatch.StartNew();
            foreach (var line in scanLines)
            {
                Console.WriteLine(line);
            }

            Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.",
                            sw.ElapsedMilliseconds);
            Console.ReadKey();
        }

        // A function that demonstrates what a fly
        // sees when it watches television :-)
        static string ExpensiveFunc(int i)
        {
            Thread.SpinWait(2000000);
            return String.Format("{0} *****************************************", i);
        }
    }
}

AutoBuffered 옵션을 사용할 경우 첫 번째 요소가 생성될 때까지 원하지 않는 지연이 발생한다면 NotBuffered 옵션을 사용하여 결과 요소를 더 빠르고 원활하게 생성할 수 있습니다.

참고 항목

참조

ParallelMergeOptions

개념

PLINQ(병렬 LINQ)

변경 기록

날짜

변경 내용

이유

2010년 5월

사용법과 속도 향상에 대한 설명을 추가했습니다.

고객 의견