トレーニング
モジュール
C# で配列と foreach ステートメントを使用して、データのシーケンスを格納し、反復処理する - Training
配列変数を作成し、配列の要素を反復処理する方法について説明します。
このブラウザーはサポートされなくなりました。
Microsoft Edge にアップグレードすると、最新の機能、セキュリティ更新プログラム、およびテクニカル サポートを利用できます。
次の例では、ツリー データ構造を走査する並列タスクを使用する 2 つの方法を示します。 ツリー自体の作成は、演習として残しておきます。
public class TreeWalk
{
static void Main()
{
Tree<MyClass> tree = new Tree<MyClass>();
// ...populate tree (left as an exercise)
// Define the Action to perform on each node.
Action<MyClass> myAction = x => Console.WriteLine("{0} : {1}", x.Name, x.Number);
// Traverse the tree with parallel tasks.
DoTree(tree, myAction);
}
public class MyClass
{
public string Name { get; set; }
public int Number { get; set; }
}
public class Tree<T>
{
public Tree<T> Left;
public Tree<T> Right;
public T Data;
}
// By using tasks explicitly.
public static void DoTree<T>(Tree<T> tree, Action<T> action)
{
if (tree == null) return;
var left = Task.Factory.StartNew(() => DoTree(tree.Left, action));
var right = Task.Factory.StartNew(() => DoTree(tree.Right, action));
action(tree.Data);
try
{
Task.WaitAll(left, right);
}
catch (AggregateException )
{
//handle exceptions here
}
}
// By using Parallel.Invoke
public static void DoTree2<T>(Tree<T> tree, Action<T> action)
{
if (tree == null) return;
Parallel.Invoke(
() => DoTree2(tree.Left, action),
() => DoTree2(tree.Right, action),
() => action(tree.Data)
);
}
}
Imports System.Threading.Tasks
Public Class TreeWalk
Shared Sub Main()
Dim tree As Tree(Of Person) = New Tree(Of Person)()
' ...populate tree (left as an exercise)
' Define the Action to perform on each node.
Dim myAction As Action(Of Person) = New Action(Of Person)(Sub(x)
Console.WriteLine("{0} : {1} ", x.Name, x.Number)
End Sub)
' Traverse the tree with parallel tasks.
DoTree(tree, myAction)
End Sub
Public Class Person
Public Name As String
Public Number As Integer
End Class
Public Class Tree(Of T)
Public Left As Tree(Of T)
Public Right As Tree(Of T)
Public Data As T
End Class
' By using tasks explicitly.
Public Shared Sub DoTree(Of T)(ByVal myTree As Tree(Of T), ByVal a As Action(Of T))
If myTree Is Nothing Then
Return
End If
Dim left = Task.Factory.StartNew(Sub() DoTree(myTree.Left, a))
Dim right = Task.Factory.StartNew(Sub() DoTree(myTree.Right, a))
a(myTree.Data)
Try
Task.WaitAll(left, right)
Catch ae As AggregateException
'handle exceptions here
End Try
End Sub
' By using Parallel.Invoke
Public Shared Sub DoTree2(Of T)(ByVal myTree As Tree(Of T), ByVal myAct As Action(Of T))
If myTree Is Nothing Then
Return
End If
Parallel.Invoke(
Sub() DoTree2(myTree.Left, myAct),
Sub() DoTree2(myTree.Right, myAct),
Sub() myAct(myTree.Data)
)
End Sub
End Class
示した 2 つのメソッドは、機能的に同等です。 タスクを作成して実行するために、StartNew メソッドを使用すると、タスクで待機し、例外を処理するために使用するタスクからハンドルを戻すことができます。
.NET に関するフィードバック
.NET はオープンソース プロジェクトです。 フィードバックを提供するにはリンクを選択します。
トレーニング
モジュール
C# で配列と foreach ステートメントを使用して、データのシーケンスを格納し、反復処理する - Training
配列変数を作成し、配列の要素を反復処理する方法について説明します。