C# Thread.CurrentThread.Name 这个属性只能设置一次

C# Thread.CurrentThread.Name 这个属性只能设置一次

Posted on May 9, 2012

今天遇到这么一个奇怪的问题:

System.InvalidOperationException
            Message="This property has already been set and cannot be modified."
            Source="mscorlib"
            StackTrace:
                 at System.Threading.Thread.set_Name(String value)
                 at TwitterRadio.TwitterRadioUI..ctor() in D:ProjTextNormalization_DEMOTwitteRadio_WPFUITwitterRadioUI.xaml.cs:line 41
            InnerException:

就是在我某一句更改当前线程名称的语句

Thread.CurrentThread.Name = "Thread_MainUI";

的时候发生了错误。说啥 “This property has already been set and cannot be modified.

于是查了查,有人说这是因为不能在线程Working的时候改名字(这个说法不准确!)。

我现在查到的答案是:

Thread.Name这个属性,只能更改一次。你可以在任意时刻更改这个属性,但只有一次改的机会。当你第二次改的时候,就会抛出这个错误,比如以下这一系列语句可以很轻易重现这个错误:

Thread.CurrentThread.Name = "Thread_MainUI1";   //OK
Thread.CurrentThread.Name = "Thread_MainUI2";   //Wrong! Exception will be thrown

为什么有这个规定?我也不是很清楚,不过查到这么一个帖子(Why is Thread.Name a write-once property?),说是频繁给线程改名字(确实啊,没事乱改什么名字),会混淆debugger之类的东西。

发布了16 篇原创文章 · 获赞 208 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/cxu123321/article/details/103885693