Top / JUNK / Parallel

MySQL で Parallel.For を使ってクエリを並列実行する例

MySQL のコネクションって複数のクエリ呼び出しが出来ないようです。

using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace WindowsFormsApp1
{
    static class Program
    {
        [STAThread]
        static void Main() {
            var parallels = 5;
            var c = new MySqlConnectionStringBuilder();
            var builder = new MySqlConnectionStringBuilder {
                UserID = "koz",
                Password = "koz",
                Server = "localhost",
                Database = "koz",
                Pooling = true,
                MinimumPoolSize = (uint)parallels,
                MaximumPoolSize = (uint)parallels
            };

            var sqlCount = 5;
            var sqls = new string[sqlCount];
            var dataTables = new DataTable[sqlCount];
            sqls[0] = "select * from A";
            sqls[1] = "select * from B";
            sqls[2] = "select * from C";
            sqls[3] = "select * from D";
            sqls[4] = "select * from E";

            ParallelFill(builder.ConnectionString, parallels, sqls, dataTables);
        }

        public static void ParallelFill(
                                string connectionString,
                                int parallels,
                                string[] sqls,
                                DataTable[] dataTables) {
            var option = new ParallelOptions();
            option.MaxDegreeOfParallelism = parallels;
            Parallel.For(0, sqls.Length, option,
                i => {
                    using (var connection = new MySqlConnection(connectionString)) {
                        connection.Open();
                        using (var command = new MySqlCommand(sqls[i], connection)) {
                            using (var adapter = new MySqlDataAdapter(command)) {
                                var dt = new DataTable();
                                adapter.Fill(dt);
                                dataTables[i] = dt;
                            }
                        }
                    }
                });
        }
    }
}



トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   最終更新のRSS
Last-modified: 2019-08-11 (日) 22:27:55 (7d)