当前位置:编程学习 > C#/ASP.NET >>

c#多线实例

using System;
using System.Threading;
using System.Text;

namespace ControlThread
{
    class Program
    {
        private static void DisplayMessage()
        {

            // 在控制台上重复显示一条消息.
            while (true)
            {

                try
                {

                    Console.WriteLine("{0} : 第二个线程正在运行,请输入"
                        + " (S)uspend, (R)esume, (I)nterrupt, or (E)xit.",
                        DateTime.Now.ToString("HH:mm:ss.ffff"));

                    // 睡眠 2 秒种.
                    Thread.Sleep(2000);

                }
                catch (ThreadInterruptedException)
                {

                    // 线程被中断. 捕获到ThreadInterruptedException异常后
                    // 示例会执行合适的行为并且继续执行.
                    Console.WriteLine("{0} : 第二个线程被中断.",
                        DateTime.Now.ToString("HH:mm:ss.ffff"));

                }
                catch (ThreadAbortException abortEx)
                {

                    // ThreadAbortException对象.
                    //线程调用Thread.Abort后所提供的ExceptionState属性
                    //本例中是包含了一个终止原因的字符串
                    Console.WriteLine("{0} : 第二个线程被终止. ({1})",
                        DateTime.Now.ToString("HH:mm:ss.ffff"),
                        abortEx.ExceptionState);

                    // 尽管 ThreadAbortException已经被处理, www.zzzyk.com
                    //运行时还是会抛出一个异常以确保线程被终止.

                }
            }

        }

        static void Main(string[] args)
        {
            // 创建一个新的线程对象,
            // 传递给他一个执行显示消息方法的ThreadStart委托实列.
          
            Thread thread = new Thread(new ThreadStart(DisplayMessage));

            Console.WriteLine("{0} : 启动第二个线程.",
                DateTime.Now.ToString("HH:mm:ss.ffff"));

            // 启动第二个线程.
            thread.Start();

            // 循环处理用户输入的命令.
            char command = ' ';

            do
            {

                string input = Console.ReadLine();
                if (input.Length > 0) command = input.ToUpper()[0];
                else command = ' ';

                switch (command)
                {

                    case 'S':
                        // 挂起第二个线程.
                        Console.WriteLine("{0} : 挂起第二个线程.",
                            DateTime.Now.ToString("HH:mm:ss.ffff"));
                        thread.Suspend();
                        break;

                    case 'R':
                   &nb

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,