多线程

在处理耗时任务时,往往会出现卡死的情况,这样的用户体验很不好,所以通常使用多线程来解决该问题。

了解多线程之前,首先要搞清楚进程和线程的区别,具体区别参考:

http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html

 

示例:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace QYH_Thread
{
    class Program
    {
        public static void ThreadProc()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadProc:" + i);
                Thread.Sleep(0);
            }
        }

        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(ThreadProc));
            t.Name = "t1";
            t.Start();

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("Main thread:Do some work.");
                Thread.Sleep(0);
            }

            Console.WriteLine("Main thread:Call Join(),to until ThreadProc ends.");

            t.Join();

            Console.WriteLine("Main thread:ThreadProc.Join has returned.");

            //Console.WriteLine(str1);
            Console.Read();

        }
    }
}
View Code

 

posted @ 2016-03-14 18:45  齐_大圣  阅读(211)  评论(0编辑  收藏  举报