2009年8月5日 星期三

Parallel C# Insert SQL

以下.Net 3.5支援平行運算的寫法
.Net 4.0可以再作跟細的Config。
昨天測試的結果
Select 作10萬次是從38秒降到23秒。

Insert 同一個Table 1萬次(這個Table有設定一個Raw(32)的PK,為了測會不會Table Lock Error!) 1萬次 從180秒降到48秒。

觀查他Connection的用量

Insert時 它同時打開6個Connection...........
以後如果有一些效能考量的程式
不妨可以試看看

/*
* Created by SharpDevelop.
* User: Yup
* Date: 2009/8/5
* Time: ¤U¤E 12:24
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Data.OracleClient;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelTry
{
        class Program
        {
                public static void Main(string[] args)
                {
                        List<string> items=new List<string>();
                        for(int i=0;i<1000;i++)
                        {
                                items.Add(i.ToString());
                        }
                        Console.WriteLine("Parallel Start!");
                        //1000個loop將被拆成2個500次的task. 會拆成幾次沒有特別指定 會自動判斷,在此用2次為例
                        Parallel.ForEach<string,OracleConnection>(
                                //Sources
                                items,
                                //localInit 只會在Task進入時執行一次。
                                ()=>{
                                        OracleConnection conn=new OracleConnection("connection string");
                                        conn.Open();//500次loop共用一個Connection.
                                        return conn;
                                },
                                //Action 在一個Task裡被執行500次。
                                (item,index,state)=>{
                                        try
                                        {
                                                using(OracleCommand cmd=new OracleCommand("SQL",state.ThreadLocalState))
                                                {
                                                        //Do Something.......................
                                                        cmd.ExecuteNonQuery();
                                                }
                                        }
                                        catch
                                        {
                                                state.Stop();//中斷所有平行運
                                        }
                                },
                                //localFinally Task結束時執行一次。 
                                finallyConn=>{
                                        finallyConn.Close();
                                }          
                        );
                        Console.Write("Press any key to continue . . . ");
                        Console.ReadKey(true);
                }
        }
}

沒有留言: