C# 多线程

C# 开启多线程的方式

1.异步委托开启线程(BeginInvoke)

        static void Main(string[] args)
        {
            //1.赋值方法
            //Action<int, int> a = add;    //add是定义的一个方法
            //2.lambda
            Action<string> action = t =>
            {
                for (int k = 0; k < 1000000000; k++)
                { }
                Console.WriteLine("当前参数是{0},当前线程是{1}", t, Thread.CurrentThread.ManagedThreadId);
            };
            //3.delegate
            //private delegate int NewTaskDelegate(int a, int b);
            //NewTaskDelegate task = add;
            //IAsyncResult asyncResult = task.BeginInvoke(20, 20, null, null);

            action.BeginInvoke("参数是", null, null);
            Console.WriteLine("----------主程序结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);
            Console.Read();
        }

2.Thread

        static void Main1(string[] args)
        {
            Console.WriteLine("----------主程序开始,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            //1.带参数
            ParameterizedThreadStart threadStart = t =>
            {
                for (int k = 0; k < 1000000000; k++)
                { }
                Console.WriteLine("当前参数是{0},当前线程是{1}", t, Thread.CurrentThread.ManagedThreadId);
            };
            Thread thread = new Thread(threadStart);
            thread.Start(1);

            //2.不带参数
            //Thread mythread = new Thread(ThreadMain);    //ThreadMain外部定义不带参数的方法
            //mythread.Start();

            //3.lambda
            //Thread thread = new Thread(() => startBuffering(ratio, ratious, thickness));
            ////thread.Priority = ThreadPriority.Lowest;
            //thread.IsBackground = true;
            //thread.Start();

            Console.WriteLine("----------主程序结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

        }

后台线程与前台线程并没有本质的区别,它们之间唯一的区别就是:后台线程不会防止应用程序的进程被终止掉。就是当前台线程都结束了的时候,整个程序也就结束了,即使还有后台线程正在运行,此时,所有剩余的后台线程都会被停止且不会完成.但是,只要还有一个前台线程没有结束,那么它将阻止程序结束.应用程序进程的存亡由前台线程决定而于后台线程无关.

3.ThreadPool线程池

        static void Main2(string[] args)
        {

            //1.
            WaitCallback waitCallback = t =>
                {
                    for (int k = 0; k < 1000000000; k++)
                    { }
                    Console.WriteLine("当前参数是{0},当前线程是{1}", t, Thread.CurrentThread.ManagedThreadId);
                };

            ThreadPool.QueueUserWorkItem(waitCallback, 2);

            //2.
            ThreadPool.QueueUserWorkItem(new WaitCallback((a) =>
            {
                Console.WriteLine("WorkItem1-Start【ThreadId=" + Thread.CurrentThread.ManagedThreadId + "】:" + DateTime.Now);
                Thread.Sleep(2000);
                Console.WriteLine("WorkItem1-End【ThreadId=" + Thread.CurrentThread.ManagedThreadId + "】:" + DateTime.Now);
            }));
            Console.Read();
        }

4.Task

//1.通过start启动
var task1 = new Task(() =>
{
    //TODO you code
})
task1.start();
//2.直接运行
var task2 = Task.Factory.StartNew(() =>
{
    //TODO you code
});

//3.
task.Wait();
task.WaitAll();
Task.WaitAny();
Task.ContinueWith();  



//4.获取task结果
var SendFeedBackTask = Task.Factory.StartNew(() => { Console.WriteLine("Get some Data!"); }).ContinueWith<bool>(s => { return true; }).ContinueWith<string>(r => 
                              {
                                 if (r.Result)
                                 {
                                    return "Finished";
                                 }
                                 else
                                 {
                                    return "Error";
                                 }
                              });

//5.Task 的取消
//IsCancellationRequested
//https://johnthiriet.com/cancel-asynchronous-operation-in-csharp/


//6.返回值
//Task<TResult>就是有返回值的Task,TResult就是返回值类型


Task<string> task = Task<string>.Run(() => {
    Thread.Sleep(2000); 
    return Thread.CurrentThread.ManagedThreadId.ToString(); 
});

5.Parallel

        static void Main3(string[] args)
        {

            Action action1 = () =>
            {
                for (int k = 0; k < 1000000000; k++)
                { }
                Console.WriteLine("当前参数是1,当前线程是{0}", Thread.CurrentThread.ManagedThreadId);
            };
            Action action2 = () =>
            {
                for (int k = 0; k < 1000000000; k++)
                { }
                Console.WriteLine("当前参数是2,当前线程是{0}", Thread.CurrentThread.ManagedThreadId);
            };
            Action action3 = () =>
            {
                for (int k = 0; k < 1000000000; k++)
                { }
                Console.WriteLine("当前参数是3,当前线程是{0}", Thread.CurrentThread.ManagedThreadId);
            };

            Parallel.Invoke(action1, action2, action3);

            Console.Read();
        }

参考:
https://www.cnblogs.com/yangxi1081/p/9639958.html

上一篇:AwaitAsync(异步和多线程)


下一篇:c# parallel.for怎么控制并发数量,控制多5个并发量