Net之多线程用法

1.多线程

2.线程池

3.Task

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics;

namespace MyThreads
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TestMethod()
        {
            int sum = 0;
            for (int i = 1; i < 100; i++)
            {
                sum += i;
            }
            Console.WriteLine("TestMethod当前线程的Id={0},sum= {1}", Thread.CurrentThread.ManagedThreadId, sum);
        }
        private void TestThread(string name)
        {
            int sum = 0;
            for (int i = 1; i < 100; i++)
            {
                sum += i;
            }
            Console.WriteLine("{0}当前线程的Id={1},sum= {2}", name,Thread.CurrentThread.ManagedThreadId, sum);
        }
        private void brtThread_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("这里是单线程");
            for (int i = 0; i < 5; i++)
            {
                TestMethod();
            }
        }
        private void brtMutriThread_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("这里是多线程");
            Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
            List<Thread> threadList = new List<Thread>();
            ThreadStart threadStart = () => TestMethod();
            for (int i = 0; i < 5; i++)
            {
                Thread thread = new Thread(threadStart);
                threadList.Add(thread);
                thread.Start();
            }
            threadList.ForEach(t => t.Join());
            Console.WriteLine(string.Format("brtMutriThread_Click已结束,可以执行其他动作当前线程的id={0}",
                Thread.CurrentThread.ManagedThreadId));
            sw.Stop();
            Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
        }

        private void brtThreadPool_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("这里是多线程");
            Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
           //线程池
            //ThreadPool.QueueUserWorkItem(t => TestThread("ThreadPool1"));
            //ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool2");
            //ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool3");
            //ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool4");
            //ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool5");

            using (ManualResetEvent m1 = new ManualResetEvent(false))
            using (ManualResetEvent m2 = new ManualResetEvent(false))
            using (ManualResetEvent m3 = new ManualResetEvent(false))
            using (ManualResetEvent m4 = new ManualResetEvent(false))
            using (ManualResetEvent m5 = new ManualResetEvent(false))
            {
                ThreadPool.QueueUserWorkItem(t => {
                    TestThread("ThreadPool1");
                    m1.Set();
                });
                ThreadPool.QueueUserWorkItem(t => {
                    TestThread("ThreadPool2");
                    m2.Set();
                });
                ThreadPool.QueueUserWorkItem(t =>
                {
                    TestThread("ThreadPool3");
                    m3.Set();
                });
                ThreadPool.QueueUserWorkItem(t =>
                {
                    TestThread("ThreadPool4");
                    m4.Set();
                });
                ThreadPool.QueueUserWorkItem(t =>
                {
                    TestThread("ThreadPool5");
                    m5.Set();
                });
                m1.WaitOne();
                m2.WaitOne();
                m3.WaitOne();
                m4.WaitOne();
                m5.WaitOne();
            }
            Console.WriteLine(string.Format("brtMutriThread_Click已结束,可以执行其他动作当前线程的id={0}",
                Thread.CurrentThread.ManagedThreadId));
            sw.Stop();
            Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
        }

// task本质是基于线程池的,只是API被强化
private void brnTask_Click(object sender, RoutedEventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("这里是多线程");
Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
//Task
List<Task> taskList = new List<Task>();
TaskFactory taskFactory = new TaskFactory();
for (int i = 0; i < 5;i++ )
{
taskList.Add(taskFactory.StartNew(() => TestThread("Task")));
}
Task.WaitAll(taskList.ToArray());



Console.WriteLine(string.Format("brnTask_Click已结束,可以执行其他动作当前线程的id={0}",
Thread.CurrentThread.ManagedThreadId));
sw.Stop();
Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
}


    }
}

<Window x:Class="MyThreads.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="350">
<Grid>
<Button Content="单线程" Height="23" HorizontalAlignment="Left" Margin="108,63,0,0" Name="brtThread" VerticalAlignment="Top" Width="75" Click="brtThread_Click" />
<Button Content="多线程" Height="23" HorizontalAlignment="Left" Margin="108,112,0,0" Name="brtMutriThread" VerticalAlignment="Top" Width="75" Click="brtMutriThread_Click" />
<Button Content="线程池" Height="23" HorizontalAlignment="Left" Margin="108,168,0,0" Name="brtThreadPool" VerticalAlignment="Top" Width="75" Click="brtThreadPool_Click" />
<Button Content="Task" Height="23" HorizontalAlignment="Left" Margin="108,216,0,0" Name="brnTask" VerticalAlignment="Top" Width="75" Click="brnTask_Click" />
</Grid>
</Window>

原文地址:https://www.cnblogs.com/gylhaut/p/5823945.html