1、codeproject上面一个多线程执行sql的库。

     开发中常常要执行一些耗时的数据操作,比如update、insert、bulk insert、index creation,

     若顺序执行,则操作总时间是每个单独sql的时间之和  为了加快速度,采用线程池异步执行的做法,比如要要create 10个表以及加数据,则可以开10个线程去分别执

 codeproject上库源码地址 http://www.codeproject.com/Articles/29356/Asynchronous-T-SQL-Execution-Without-Service-Broke
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SqlClrLib.Model;

namespace ExampleTransaction
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //开发中常常要执行一些耗时的数据操作,比如update、insert、bulk insert、index creation,
            //若顺序执行,则操作总时间是每个单独sql的时间之和,
            //为了加快速度,引入异步执行的做法,比如要要create 10个表以及加数据,则可以开10个线程去分别执行
        }

        [Microsoft.SqlServer.Server.SqlProcedure]
        public static int SaveWarehouseFinalData(Guid fileDefinitionId)
        {
            Console.WriteLine("Start");
            StoredProcedures.Parallel_Declare(new SqlString("Parallel SaveWarehouseFinalData"));
            //Console.WriteLine("Database connection is ... {0}", StoredProcedures.Block.ConnectionString);
            //Console.WriteLine("Max threads count is ... {0}", StoredProcedures.Block.MaxThreads);
            ////ParallelProcedures.Block.IsTransactional = true;
            ////ParallelProcedures.Parallel_UseTransaction("Serializable");
            //依次将存储过程加入到线程池
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToEAV"), new SqlChars(string.Format("usp_WarehouseImportSaveToEAV '{0}'", fileDefinitionId)));
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToAdminHistory"), new SqlChars(string.Format("usp_WarehouseImportSaveToAdminHistory '{0}'", fileDefinitionId)));
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToValResult"), new SqlChars(string.Format("usp_WarehouseImportSaveToValResult '{0}'", fileDefinitionId)));
            //执行save操作(此处用的事务,如果不成功会回滚)
            int failedCount = StoredProcedures.Parallel_Execute();
            //Console.WriteLine("Failed count is ... {0}", failedCount);
            ResultItem[] resultItems = (ResultItem[])StoredProcedures.Parallel_GetExecutionResult();
            foreach (ResultItem r in resultItems)
            {
                //Console.WriteLine(r.ToString());
            }
            //Console.WriteLine("End...");
           
            return failedCount;
        }

    }
}

 

posted on 2015-12-14 19:24  AmyAlisa  阅读(3903)  评论(0编辑  收藏  举报