如何使用匿名方法设置线程名称?

时间:2014-08-08 19:02:37

标签: c# .net multithreading

我有以下代码从匿名方法运行我的指令进行线程化

new Thread(delegate()
    {
        //my code
    }).Start();

出于调试目的,我想在上面的场景中设置线程名称,我该如何实现呢?

感谢

4 个答案:

答案 0 :(得分:4)

new Thread(delegate()
    {
        //my code
    })
   {
      Name = "whatever"
   }.Start();

或者让它变得可读。

var thread = Thread(delegate()
             {
                 //my code
             });
thread.Name = "whatever";
thread.Start();

答案 1 :(得分:1)

委托与线程名称无关:

Thread t = new Thread(delegate()
{
    //my code
});

t.Name = "ThreadName";
t.Start();

答案 2 :(得分:1)

http://msdn.microsoft.com/en-us/library/system.threading.thread.name(v=vs.110).aspx

   var thread = Thread delegate()
       {
           //my code
       });
   thread.Name="foo";
   thread.Start();

答案 3 :(得分:1)

您有三种选择。

  • 请勿将.Start()放在同一行。
var thread = new Thread(delegate()
    {
        //my code
    });
thread.Name = "MyName";
thread.Start();
  • 编写扩展方法
static void Start(this Thread thread, string name)
{
    thread.Name = name;
    thread.Start();
}

//Elsewhere
new Thread(delegate()
{
    //my code
}).Start("MyName");