マルチスレッドでC#アプリを使用して、Parallel.ForEach
さまざまなパラメーターでspを呼び出します。3つのセクションがあります。Init、Body、localFinally
public void NearLinkParallelGeneration(avl_range avl_pending, DateTime dt_start_process)
{
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount + 2
};
// create the partition based on the input
var partitions = Partitioner
.Create(
fromInclusive: avl_pending.begin,
toExclusive: avl_pending.end,
rangeSize: 100
)
.GetDynamicPartitions();
Parallel.ForEach(
source: partitions,
parallelOptions: parallelOptions,
localInit: () =>
{
NpgsqlConnection conn = new NpgsqlConnection(strConnection);
NpgsqlCommand cmd = new NpgsqlCommand();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM avl_db.process_near_link(@begin, @end, @start_time);";
cmd.CommandType = CommandType.Text;
NpgsqlParameter p = new NpgsqlParameter("@begin", NpgsqlDbType.Bigint);
cmd.Parameters.Add(p);
p = new NpgsqlParameter("@end", NpgsqlDbType.Bigint);
cmd.Parameters.Add(p);
p = new NpgsqlParameter("@start_time", NpgsqlDbType.Timestamp);
p.Value = dt_start_process;
cmd.Parameters.Add(p);
}
catch (NpgsqlException ex)
{
Console.WriteLine(ex.InnerException);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.InnerException);
}
return new { Connection = conn, Command = cmd };
},
body: (source, state, local) =>
{
if (local.Connection.State == ConnectionState.Open)
{
string strResult = String.Format("From: {0} - To: {1}", source.Item1, source.Item2);
Console.WriteLine(strResult);
try
{
local.Command.Parameters["@begin"].Value = source.Item1;
local.Command.Parameters["@end"].Value = source.Item2;
local.Command.ExecuteNonQuery();
}
catch (NpgsqlException ex)
{
Console.WriteLine(ex.InnerException);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.InnerException);
}
//strResult = String.Format("DONE From: {0} - To: {1}", source.Item1, source.Item2);
//Console.WriteLine(strResult);
}
return local;
},
localFinally: local =>
{
local.Command?.Dispose();
local.Connection?.Dispose();
}
);
}