CodeTrigger  

Code Generation For C#, WPF, WCF, SQL SERVER/ORACLE/MYSQL and Visual Studio 2013-2019

Code Sample: MultiThreading & the Unit of Work Pattern with CodeTrigger
A code sample showing a multi-threaded implementation using CodeTrigger and the unit of work pattern
This sample assumes you have run through the steps in the unit-of-work sample
                    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace UnitOfWorkSample
{
    class Program
    {
        static Random rand = new Random();
        static void Main(string[] args)
        {
           for(int k = 0; k < 10; k++)
           {
               Thread workerThread = new Thread(DoWork);
               workerThread.Start((object)"Thread" + k.ToString());
           }
           Console.ReadLine();
        }
        
        static void DoWork(object oThreadName)
        {
            string threadName = (string)oThreadName;
            IUnitOfWork uow = new UnitOfWorkImp();
            IList<string> listIds = new List<string>();
            for(int k = 0; k < 100; k++)
            {
                BOProducts prod = new BOProducts();
                prod.CategoryID = 1;
                prod.ProductName = "test";
                prod.SupplierID = 1;
                prod.UnitPrice = 10M;
                prod.Discontinued = false;
                uow.Create(prod);
                uow.Create(new UnitOfWorkForwarder((Action)delegate { listIds.Add("'" + prod.ProductID + "'"); }, null, null));
                Console.WriteLine("Thread " + threadName + " created product " + k);
                Thread.Sleep(rand.Next(100, 1000));
                
            }

            string outErr;
            if(!uow.Commit(out outErr))
                throw new Exception(outErr);

            Console.WriteLine("Thread " + threadName + " committed transaction.");
            IList<BOProducts> listProds = new Criteria<BOProducts>()
                .Add(Expression.In("ProductID", string.Join(",", listIds.ToArray())))
                .List<BOProducts>();

            Console.WriteLine("Thread " + threadName + " found " + listProds.Count + " objects committed in db");

            uow = new UnitOfWorkImp();
            foreach(var prod in listProds)
                uow.Delete(prod);

            if (!uow.Commit(out outErr))
                throw new Exception(outErr);

            Console.WriteLine("Thread " + threadName + " deleted all its products successfully");
        }
    }
}