Specifying a Thread's Name when using Task.StartNew

萝らか妹 提交于 2019-12-09 07:34:56

问题


Is there a way to specify a Thread's name when using the Task.StartNew method

var task = Task.Factory.StartNew(MyAction, TaskCreationOption.LongRunning, ??ThreadName??);

回答1:


Not a Thread-name for sure.

Threads and tasks are not 1-to-1 related.

You can use the Task.Id to track it.




回答2:


Well, this works:

class Program {
    static void Main(string[] args) {
        var task = Task.Factory.StartNew(() => {
            Thread.CurrentThread.Name = "foo";
            Thread.Sleep(10000);   // Use Debug + Break to see it
        });
        task.Wait();
    }
}

There's a problem however, the threadpool thread gets recycled and won't change its name. This can be confusing, you'll see it running later executing entirely different code. Be sure to take note of this. Your best bet is otherwise to use the Location column in the Debug + Windows + Threads window to find the task back.




回答3:


I prefer to use Thread.CurrentThread.ManagedThreadId. It's not as good as a name, but does help track the specific work for a thread.




回答4:


Tasks use the threadpool and a thread can be named only once. What you can do is use a ThreadStatic variable. It will however live between tasks, so set it in every task again.




回答5:


You could write your own TaskScheduler which sets Thread.CurrentThread.Name when it puts a task on a thread. After the task is done your custom TaskScheduler can also clear Thread.CurrentThread.Name to avoid any confusion.



来源:https://stackoverflow.com/questions/8038325/specifying-a-threads-name-when-using-task-startnew

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!