이 예제에서는 작업 병렬 라이브러리의 ParallelInvoke()를 사용하여 작업을 병렬화하는 방법을 보여 줍니다. 세 가지 작업이 공유 데이터 소스에서 수행됩니다. 이 중 어느 작업도 소스를 수정하지는 않으므로 간단한 방법으로 세 작업을 병렬로 실행할 수 있습니다.
![]() |
---|
이 문서에서는 람다 식을 사용하여 TPL에 대리자를 정의합니다.C# 또는 Visual Basic의 람다 식에 익숙하지 않으면 PLINQ 및 TPL의 람다 식을 참조하십시오. |
예제
' How to: Use Parallel.Invoke to Execute Parallel Operations
Option Explicit On
Option Strict On
Imports System.Threading.Tasks
Imports System.Net
Module ParallelTasks
Sub Main()
' Retrieve Darwin's "Origin of the Species" from Gutenberg.org.
Dim words As String() = CreateWordArray("http://www.gutenberg.org/files/2009/2009.txt")
'#Region "ParallelTasks"
' Perform three tasks in parallel on the source array
Parallel.Invoke(Sub()
Console.WriteLine("Begin first task...")
GetLongestWord(words)
' close first Action
End Sub,
Sub()
Console.WriteLine("Begin second task...")
GetMostCommonWords(words)
'close second Action
End Sub,
Sub()
Console.WriteLine("Begin third task...")
GetCountForWord(words, "species")
'close third Action
End Sub)
'close parallel.invoke
Console.WriteLine("Returned from Parallel.Invoke")
'#End Region
Console.WriteLine("Press any key to exit")
Console.ReadKey()
End Sub
#Region "HelperMethods"
Sub GetCountForWord(ByVal words As String(), ByVal term As String)
Dim findWord = From word In words _
Where word.ToUpper().Contains(term.ToUpper()) _
Select word
Console.WriteLine("Task 3 -- The word ""{0}"" occurs {1} times.", term, findWord.Count())
End Sub
Sub GetMostCommonWords(ByVal words As String())
Dim frequencyOrder = From word In words _
Where word.Length > 6 _
Group By word
Into wordGroup = Group, Count()
Order By wordGroup.Count() Descending _
Select wordGroup
Dim commonWords = From grp In frequencyOrder
Select grp
Take (10)
Dim s As String
s = "Task 2 -- The most common words are:" & vbCrLf
For Each v In commonWords
s = s & v(0) & vbCrLf
Next
Console.WriteLine(s)
End Sub
Function GetLongestWord(ByVal words As String()) As String
Dim longestWord = (From w In words _
Order By w.Length Descending _
Select w).First()
Console.WriteLine("Task 1 -- The longest word is {0}", longestWord)
Return longestWord
End Function
' An http request performed synchronously for simplicity.
Function CreateWordArray(ByVal uri As String) As String()
Console.WriteLine("Retrieving from {0}", uri)
' Download a web page the easy way.
Dim s As String = New WebClient().DownloadString(uri)
' Separate string into an array of words, removing some common punctuation.
Return s.Split(New Char() {" "c, ControlChars.Lf, ","c, "."c, ";"c, ":"c, _
"-"c, "_"c, "/"c}, StringSplitOptions.RemoveEmptyEntries)
End Function
#End Region
' Output (May vary on each execution):
' Retrieving from http://www.gutenberg.org/dirs/etext99/otoos610.txt
' Response stream received.
' Begin first task...
' Begin second task...
' Task 2 -- The most common words are:
' species
' selection
' varieties
' natural
' animals
' between
' different
' distinct
' several
' conditions
'
' Begin third task...
' Task 1 -- The longest word is characteristically
' Task 3 -- The word "species" occurs 1927 times.
' Returned from Parallel.Invoke
' Press any key to exit
'
End Module
namespace ParallelTasks
{
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
class ParallelInvoke
{
static void Main()
{
// Retrieve Darwin's "Origin of the Species" from Gutenberg.org.
string[] words = CreateWordArray(@"http://www.gutenberg.org/files/2009/2009.txt");
#region ParallelTasks
// Perform three tasks in parallel on the source array
Parallel.Invoke(() =>
{
Console.WriteLine("Begin first task...");
GetLongestWord(words);
}, // close first Action
() =>
{
Console.WriteLine("Begin second task...");
GetMostCommonWords(words);
}, //close second Action
() =>
{
Console.WriteLine("Begin third task...");
GetCountForWord(words, "species");
} //close third Action
); //close parallel.invoke
Console.WriteLine("Returned from Parallel.Invoke");
#endregion
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
#region HelperMethods
private static void GetCountForWord(string[] words, string term)
{
var findWord = from word in words
where word.ToUpper().Contains(term.ToUpper())
select word;
Console.WriteLine(@"Task 3 -- The word ""{0}"" occurs {1} times.",
term, findWord.Count());
}
private static void GetMostCommonWords(string[] words)
{
var frequencyOrder = from word in words
where word.Length > 6
group word by word into g
orderby g.Count() descending
select g.Key;
var commonWords = frequencyOrder.Take(10);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Task 2 -- The most common words are:");
foreach (var v in commonWords)
{
sb.AppendLine(" " + v);
}
Console.WriteLine(sb.ToString());
}
private static string GetLongestWord(string[] words)
{
var longestWord = (from w in words
orderby w.Length descending
select w).First();
Console.WriteLine("Task 1 -- The longest word is {0}", longestWord);
return longestWord;
}
// An http request performed synchronously for simplicity.
static string[] CreateWordArray(string uri)
{
Console.WriteLine("Retrieving from {0}", uri);
// Download a web page the easy way.
string s = new WebClient().DownloadString(uri);
// Separate string into an array of words, removing some common punctuation.
return s.Split(
new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' },
StringSplitOptions.RemoveEmptyEntries);
}
#endregion
}
/* Output (May vary on each execution):
Retrieving from http://www.gutenberg.org/dirs/etext99/otoos610.txt
Response stream received.
Begin first task...
Begin second task...
Task 2 -- The most common words are:
species
selection
varieties
natural
animals
between
different
distinct
several
conditions
Begin third task...
Task 1 -- The longest word is characteristically
Task 3 -- The word "species" occurs 1927 times.
Returned from Parallel.Invoke
Press any key to exit
*/
}
Invoke()를 사용할 경우 동시에 실행할 작업을 표현하기만 하면 호스트 컴퓨터의 코어 수에 맞게 자동으로 확장하는 작업을 비롯한 모든 스레드 예약 세부 사항이 런타임에서 자동으로 처리됩니다.
이 예제에서는 데이터가 아니라 작업을 병렬화합니다. PLINQ를 사용하여 LINQ 쿼리를 병렬화하고 쿼리를 순차적으로 실행할 수도 있습니다. 또는 PLINQ를 사용하여 데이터를 병렬화할 수도 있습니다. 또 다른 방법은 쿼리와 작업을 모두 병렬화하는 것입니다. 이때 발생하는 오버헤드로 인해 프로세서 수가 비교적 적은 호스트 컴퓨터에서 성능이 저하될 수 있지만 프로세서 수가 많은 컴퓨터에서는 성능이 훨씬 더 향상됩니다.
코드 컴파일
- 전체 예제를 복사한 다음 Microsoft Visual Studio 2010 프로젝트에 붙여넣고 F5 키를 누릅니다.