C# 多线程Demo

1.启动线程
Thread thread1 = new Thread(new ThreadStart( Count));

2.杀死线程
在杀死一个线程前最好先判断它是否还活着(IsAlive 属性),调用 Abort 方法来杀死此线程
if ( thread.IsAlive )
  {
  thread.Abort();
  }

3.暂停线程
thread.Sleep(1000);

4.优先级
优先级可分为5种:Lowest,BelowNormal,Normal, AboveNormal,  Highest。
例如:thread.Priority = ThreadPriority.Highest;

5.挂起线程
用Suspend方法用来挂起线程,调用Resume此线程才可以继续执行。
if (thread.ThreadState = ThreadState.Running)
    {
         thread.Suspend();
    }

if (thread.ThreadState = ThreadState.Suspended)
    {
         thread.Resume();
    }

以上资料出处:http://www.knowsky.com/4709.html

 

具体例子:

static void Main()
        {
            Thread thread1 = new Thread(new ThreadStart(Method1));
            Thread thread2 = new Thread(new ThreadStart(Method2));
            thread1.Start();

            thread1.Join();        //线程1十次循环完成,再做线程2(省去此句,可使两线程执行进度相同,因为执行有延时)
            thread2.Start();

            Console.ReadLine();

        }
        public static void Method1()
        {
            try
            {
                int i;
                for (i = 0; i < 10; i++)
                {
                    Console.WriteLine("Method1 at :" + i.ToString());
                    DelayTime(1);  //延长时间,模拟执行任务              

}
            }
            catch (System.Threading.ThreadAbortException)
            {
                Console.WriteLine("进程1马上将被强制杀死!");
            }
        }

        public static void Method2()
        {
            int i;
            for (i = 0; i < 10; i++)
            {
                Console.WriteLine("Method2 at :" + i.ToString());
                DelayTime(1);  //延长时间,模拟执行任务
            }
        }

        private static void DelayTime(int n)
        {
            DateTime startTime = DateTime.Now;
            while (startTime.AddSeconds(n) > DateTime.Now)
            {
                //延长时间,模拟实际中的进程
            }
        }

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s