c#多线程

        #region 同步、异步
        static void Calculator(string name)
        {
            //throw (new Exception("Test"));
            Console.WriteLine("Calculate Start,Name:" + name + ",Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int result = 0;
            for (int i = 1; i < 999999999; i++)
            {
                result += i;
            }
            sw.Stop();
            Console.WriteLine("Calculate Stop,Name:" + name + ",Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Result:" + result + ",Time" + sw.Elapsed);
        }
        delegate void CalculatorDel(string name);
        static void Invoke()
        {
            Console.WriteLine("Invoke Start,Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            CalculatorDel del1 = Calculator;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 1; i < 6; i++)
            {
                del1.Invoke("Thread" + i);
            }
            sw.Stop();
            Console.WriteLine("Invoke Stop,Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Time:" + sw.Elapsed);
        }
        static void BeginInvoke()
        {
            Console.WriteLine("BeginInvole Start,Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            CalculatorDel del2 = Calculator;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            List<IAsyncResult> ResultList = new List<IAsyncResult>();
            for (int i = 1; i < 6; i++)
            {
                ResultList.Add(del2.BeginInvoke("Thread" + i, null, null));
            }
            ResultList.ForEach(q =>
            {
                del2.EndInvoke(q);
            });
            sw.Stop();
            Console.WriteLine("BeginInvoke Stop,Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Time:" + sw.Elapsed);
        }
        static void Tasks()
        {
            Console.WriteLine("Tasks Start,Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            TaskFactory factory = new TaskFactory();
            List<Task> taskList = new List<Task>();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                for (int i = 1; i < 6; i++)
                {
                    int k = i;
                    Action act = () =>
                    {
                        if (k == 3)
                        {
                            cts.Cancel();
                            //throw new Exception("test");
                        }
                        Calculator("Task" + k);
                    };
                    taskList.Add(factory.StartNew(act, cts.Token));
                    //Action<object> q = t => Calculator("");
                    //Action a = () =>
                    //{
                    //    Calculator("");
                    //};
                    //Task t1 = factory.StartNew(() => Calculator(""), cts.Token);
                    //taskList.Add(factory.StartNew(() => Calculator(""), cts.Token));
                }
                factory.ContinueWhenAll(taskList.ToArray(), t => { Console.WriteLine("All Done"); });
                Task.WaitAll(taskList.ToArray());
            }
            catch (AggregateException aex)
            {
                foreach (var item in aex.InnerExceptions)
                {
                    Console.WriteLine(item.Message);
                }
            }
            sw.Stop();
            Console.WriteLine("Tasks Stop,Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Time:" + sw.Elapsed);
        }
        static void TaskLock()
        {
            Console.WriteLine("TaskLock Start,Thread Id:" + Thread.CurrentThread.ManagedThreadId);
            TaskFactory factory = new TaskFactory();
            List<Task> taskList = new List<Task>();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int totalCount = 0;
            List<int> listInt = new List<int>();
            object lockObj = new object();
            int interLocked = 0;
            for (int i = 0; i < 10000; i++)
            {
                int k = i;
                taskList.Add(factory.StartNew(() =>
                {
                    //lock (lockObj)
                    //{
                    Interlocked.Increment(ref interLocked);
                    totalCount += 1;
                    //List<int> newlist = new List<int>();
                    //newlist.Add(k);
                    listInt.Add(k);
                    //}
                }));
            }
            Task.WaitAll(taskList.ToArray());
            Console.WriteLine("TotalCount:" + totalCount + ",TaskCount:" + taskList.Count + ",ListCount:" + listInt.Count + ",InterLocked:" + interLocked);
            sw.Stop();
            Console.WriteLine("TaskLock Stop,Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Time:" + sw.Elapsed);
        }

        static void CountTest()
        {
            ParallelOptions option = new ParallelOptions
            {
                MaxDegreeOfParallelism = 2,
            };
            try
            {
                Parallel.For(1, 31, option, (t, obj) =>
                {
                    if (t == 1)
                    {
                        obj.Stop();
                    }
                    Thread.Sleep(100);
                    Console.WriteLine("Thread Execute,Current Page:" + t + ",Current Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Task Id:" + Task.CurrentId);
                });
            }
            catch (AggregateException age)
            {
                foreach (var item in age.InnerExceptions)
                {
                    Console.WriteLine(item.Message);
                }
            }
            //int allPage = 300;
            //TaskFactory factory = new TaskFactory();
            //List<Task> taskList = new List<Task>();
            //object lockObj = new object();
            //List<int> pageList = new List<int>();
            //for (int i = 1; i <= 5; i++)
            //{
            //    taskList.Add(factory.StartNew(() =>
            //    {
            //        //Random ren = new Random();
            //        //int k = ren.Next(1, allPage);
            //        //while (k <= allPage && !pageList.Contains(k))
            //        //{
            //        //    lock (lockObj)
            //        //    {
            //        //        pageList.Add(k);
            //        //    }
            //        //    Thread.Sleep(1000);
            //        //    TestFunc(k, pageList);
            //        //    k++;
            //        //}
            //        //TestFunc(k, allPage, lockObj);

            //        TestFunc(i, pageList);
            //    }));

            //}
            //Task.WaitAll(taskList.ToArray());
            //Console.WriteLine("Page Count:" + allPage + ",Task Count:" + taskList.Count);
        }
        static void ThreadPoolTest()
        {
            bool isRun = true;//是否需要同步
            int allPage = 50;//同步总也是
            int threadCount = 5;//最大线程数
            int alreadyPage = 0;//已同步页数
            int poolCount = 0;//当前线程池数量
            int beginNo = allPage / threadCount;
            TaskFactory factory = new TaskFactory();
            List<Task> taskList = new List<Task>();
            object lockObj = new object();
            while (isRun)
            {
                if (poolCount == 5)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (alreadyPage == allPage)
                {
                    isRun = false;
                }
                for (int i = 1; i <= threadCount; i++)
                {
                    int k = i;
                    taskList.Add(factory.StartNew(() =>
                    {

                    }));
                }
            }
        }
        static void TestFunc(int j, List<int> pageList)
        {
            int count = 0;
            for (int i = 0; i < 99999999; i++)
            {
                count += i;
            }
            Console.WriteLine("Current page:{0},thread id:{1},count:", j, Thread.CurrentThread.ManagedThreadId, count);
            //Thread.Sleep(1000);
            //Console.WriteLine("Thread Execute,Current Page:" + i + ",Current Thread Id:" + Thread.CurrentThread.ManagedThreadId + ",Task Id:" + Task.CurrentId + ",PageList Count:" + pageList.Count);
        }

        #endregion 
原文地址:https://www.cnblogs.com/zxxxx/p/7400489.html