C#多线程编程

C#多线程编程

 

1、使用线程的理由html

一、可使用线程将代码同其余代码隔离,提升应用程序的可靠性。编程

二、可使用线程来简化编码。多线程

三、可使用线程来实现并发执行。并发

2、基本知识异步

一、进程与线程:进程做为操做系统执行程序的基本单位,拥有应用程序的资源,进程包含线程,进程的资源被线程共享,线程不拥有资源。函数

二、前台线程和后台线程:经过Thread类新建线程默认为前台线程。当全部前台线程关闭时,全部的后台线程也会被直接终止,不会抛出异常。性能

三、挂起(Suspend)和唤醒(Resume):因为线程的执行顺序和程序的执行状况不可预知,因此使用挂起和唤醒容易发生死锁的状况,在实际应用中应该尽可能少用。编码

四、阻塞线程:Join,阻塞调用线程,直到该线程终止。spa

五、终止线程:Abort:抛出 ThreadAbortException 异常让线程终止,终止后的线程不可唤醒。Interrupt:抛出 ThreadInterruptException 异常让线程终止,经过捕获异常能够继续执行。操作系统

六、线程优先级:AboveNormal BelowNormal Highest Lowest Normal,默认为Normal。

3、线程的使用

线程函数经过委托传递,能够不带参数,也能够带参数(只能有一个参数),能够用一个类或结构体封装参数。

复制代码

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(TestMethod));
            Thread t2 = new Thread(new ParameterizedThreadStart(TestMethod));
            t1.IsBackground = true;
            t2.IsBackground = true;
            t1.Start();
            t2.Start("hello");
            Console.ReadKey();
        }

        public static void TestMethod()
        {
            Console.WriteLine("不带参数的线程函数");
        }

        public static void TestMethod(object data)
        {
            string datastr = data as string;
            Console.WriteLine("带参数的线程函数,参数为:{0}", datastr);
        }
    } 
}

复制代码

4、线程池

因为线程的建立和销毁须要耗费必定的开销,过多的使用线程会形成内存资源的浪费,出于对性能的考虑,因而引入了线程池的概念。线程池维护一个请求队列,线程池的代码从队列提取任务,而后委派给线程池的一个线程执行,线程执行完不会被当即销毁,这样既能够在后台执行任务,又能够减小线程建立和销毁所带来的开销。

线程池线程默认为后台线程(IsBackground)。

复制代码

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //将工做项加入到线程池队列中,这里能够传递一个线程参数
            ThreadPool.QueueUserWorkItem(TestMethod, "Hello");
            Console.ReadKey();
        }

        public static void TestMethod(object data)
        {
            string datastr = data as string;
            Console.WriteLine(datastr);
        }
    }
}

复制代码

5、Task类

使用ThreadPool的QueueUserWorkItem()方法发起一次异步的线程执行很简单,可是该方法最大的问题是没有一个内建的机制让你知道操做何时完成,有没有一个内建的机制在操做完成后得到一个返回值。为此,可使用System.Threading.Tasks中的Task类。

构造一个Task<TResult>对象,并为泛型TResult参数传递一个操做的返回类型。

复制代码

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 1000);
            t.Start();
            t.Wait();
            Console.WriteLine(t.Result);
            Console.ReadKey();
        }

        private static Int32 Sum(Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; --n)
                checked{ sum += n;} //结果太大,抛出异常
            return sum;
        }
    }
}

复制代码

一个任务完成时,自动启动一个新任务。
一个任务完成后,它能够启动另外一个任务,下面重写了前面的代码,不阻塞任何线程。

复制代码

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 1000);
            t.Start();
            //t.Wait();
            Task cwt = t.ContinueWith(task => Console.WriteLine("The result is {0}",t.Result));
            Console.ReadKey();
        }

        private static Int32 Sum(Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; --n)
                checked{ sum += n;} //结果溢出,抛出异常
            return sum;
        }
    }
}

复制代码

6、委托异步执行

委托的异步调用:BeginInvoke() 和 EndInvoke()

复制代码

namespace Test
{
    public delegate string MyDelegate(object data);
    class Program
    {
        static void Main(string[] args)
        {
            MyDelegate mydelegate = new MyDelegate(TestMethod);
            IAsyncResult result = mydelegate.BeginInvoke("Thread Param", TestCallback, "Callback Param");

            //异步执行完成
            string resultstr = mydelegate.EndInvoke(result);
        }

        //线程函数
        public static string TestMethod(object data)
        {
            string datastr = data as string;
            return datastr;
        }

        //异步回调函数
        public static void TestCallback(IAsyncResult data)
        {
            Console.WriteLine(data.AsyncState);
        }
    }
}

复制代码

7、线程同步

  1)原子操做(Interlocked):全部方法都是执行一次原子读取或一次写入操做。

  2)lock()语句:避免锁定public类型,不然实例将超出代码控制的范围,定义private对象来锁定。

  3)Monitor实现线程同步

    经过Monitor.Enter() 和 Monitor.Exit()实现排它锁的获取和释放,获取以后独占资源,不容许其余线程访问。

    还有一个TryEnter方法,请求不到资源时不会阻塞等待,能够设置超时时间,获取不到直接返回false。

  4)ReaderWriterLock

    当对资源操做读多写少的时候,为了提升资源的利用率,让读操做锁为共享锁,多个线程能够并发读取资源,而写操做为独占锁,只容许一个线程操做。

  5)事件(Event)类实现同步

    事件类有两种状态,终止状态和非终止状态,终止状态时调用WaitOne能够请求成功,经过Set将时间状态设置为终止状态。

    1)AutoResetEvent(自动重置事件)

    2)ManualResetEvent(手动重置事件)

  6)信号量(Semaphore)

      信号量是由内核对象维护的int变量,为0时,线程阻塞,大于0时解除阻塞,当一个信号量上的等待线程解除阻塞后,信号量计数+1。

      线程经过WaitOne将信号量减1,经过Release将信号量加1,使用很简单。

  7)互斥体(Mutex)

      独占资源,用法与Semaphore类似。

   8)跨进程间的同步

      经过设置同步对象的名称就能够实现系统级的同步,不一样应用程序经过同步对象的名称识别不一样同步对象。

相关文章
相关标签/搜索