LoginSignup
3
5

More than 3 years have passed since last update.

C# 並列処理 コピペ用 サンプルコード チートシート

Last updated at Posted at 2020-07-06

このまま動作します。
コピぺ、編集して利用するためのコードの断片です。
自由に使って頂いて構いません。

パターン1 - インデックス0から9までの並列処理

using System;
using System.Threading.Tasks;

// インデックス0から9までの並列処理。
Parallel.For(0, 10, i => {
    Console.WriteLine(i.ToString());
});
// 全ての並列処理が完了したら、処理がこの先へ進む。

パターン2 - リストの内容で並列処理

using System;
using System.Threading.Tasks;

// リストの内容で並列処理。
var l = new List<String>{"a", "b", "c"};
Parallel.ForEach(l, s => {
    Console.WriteLine(s);
});
// 全ての並列処理が完了したら、処理がこの先へ進む。

パターン3 - 繰り返しを使わない並列処理

using System;
using System.Threading.Tasks;

// 繰り返しを使わない並列処理。
// ここでは4つの処理を並列化しているが、処理数は自由。
Parallel.Invoke(
    () => {
        Console.WriteLine("a");
    },
    () => {
        Console.WriteLine("b");
    },
    () => {
        Console.WriteLine("c");
    },
    () => {
        Console.WriteLine("d");
    }
);
//全ての並列処理が完了したら、処理がこの先へ進む。

パターン4 - 並列処理を立ち上げる

using System;
using System.Threading.Tasks;

// 並列処理を立ち上げる。
Task.Run(() => {
    Console.WriteLine("a");
});
// 処理の終了を待たずに、処理がこの先へ進む。

パターン5 - 並列処理を立ち上げて、処理の終了を待ち合わせる

using System;
using System.Threading.Tasks;

// 並列処理を立ち上げる。
var t = Task.Run(() => {
    Console.WriteLine("a");
});

Console.WriteLine("b");

// 処理の終了を待ち合わせる所でこうする。
t.Wait();

注意事項 - 並列処理内の例外は呼び出し元でキャッチされない

using System;
using System.Threading.Tasks;

Task.Run(() => {
    //並列処理内で送出された例外は呼び出し元でキャッチされない。
    //このように、並列処理内で対処すると良い。
    try
    {
        Console.WriteLine("a");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
});
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5