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

线程的理解

我想用下面的代码理解线,但在运行时出错,错误提示是Thread.CurrentThread.Name = "附加线程"; 这里已经指定的属性值

using System.Threading;

namespace ConsoleApplication2
{
    public class Alpha
    {
        public void Beta()
        {
            while (true)
            {
                Thread.CurrentThread.Name = "附加线程";
                Console.WriteLine(Thread.CurrentThread.Name + "状态是:" + Thread.CurrentThread.ThreadState);
            }
        }
    };

    public class Simple
    {
        public static int Main()
        {
            Thread.CurrentThread.Name = "主线程";
            Alpha oAlpha = new Alpha();
            Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
            oThread.Start();
            Console.WriteLine(Thread.CurrentThread.Name);
            while (!oThread.IsAlive) ;
            Thread.Sleep(1000);
            oThread.Abort();
            oThread.Join();
            Console.WriteLine();
            Console.WriteLine("Alpha.Beta has finished");
            Console.WriteLine(Thread.CurrentThread.Name + "状态是:" + Thread.CurrentThread.ThreadState);
            try
            {
                Console.WriteLine("Try to restart the Alpha.Beta thread");
                oThread.Start();
            }
            catch (ThreadStateException)
            {
                Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
                Console.WriteLine("Expected since aborted threads cannot be restarted.");
                Console.ReadLine();
            }
            return 0;
        }
    } 
}

我在代码的多个地方使用了 Console.WriteLine(Thread.CurrentThread.Name + "状态是:" + Thread.CurrentThread.ThreadState); 目的是想查看当前在那个线程在运行。 --------------------编程问答-------------------- Thread.CurrentThread.Name = "附加线程";
挪到while前边去 --------------------编程问答-------------------- Thread.Name属性只允许赋值一次,如果你赋值多次必定出错,放在while循环内部赋值肯定会导致多次赋值,

其实你这个写法等于

Console.WriteLine("附加线程状态是:" + Thread.CurrentThread.ThreadState);
  --------------------编程问答-------------------- 如果你想知道是哪个线程,应该输出Thread.ManagedThreadId,

如果你想用Name区分是哪个线程,就应该在Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
 之后马上就给Name赋值,这时候赋值可以保证只赋值一次,
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,