如何命名运行任务的线程? [英] How to name a thread running a Task?

查看:87
本文介绍了如何命名运行任务的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现命名线程在调试时非常有用.

I find naming threads to be very useful when debugging.

我看不到使用Task.Factory.StartNew()

那么在任务中显式命名线程是否可以接受?例如:

So is it acceptable to name the thread explicitly in the task? eg:

private void MyFunc()
{
    Task.Factory.StartNew(() =>
    {
        Thread.CurrentThread.Name = "Foobulizer";
        Foobulize();
    });
}

但是,我知道线程可以重用于不同的任务,所以我需要在任务结束时显式地重置线程名称吗?这感觉很hacky,所以我认为这可能不是一个好主意,或者有适当的方法做到这一点?

However, I appreciate that threads may be reused for different tasks, so would I need to explicitly reset the thread name at the end of the task? This feels pretty hacky so I'm thinking this is probably a bad idea, or there's a proper way to do it?

推荐答案

您不能执行此操作,因为多个Task可以共享单个或多个线程,这取决于给定时间内的ThreadPool状态.基本上,Task不是线程,这只是异步操作的高级抽象.您可以使用 Task.Id 属性但是请记住,Id是只读的并且是int类型,因此您不能分配自定义的用户友好名称.

You can not do this since multiple Tasks can share single or multiple threads depends on ThreadPool state in a given moment of time. Basically Task is not a Thread this is just a high level abstraction for the asynchronous operation. You can use Task.Id property but keep in mind that Id is readonly and of int type so you can't assign custom user-friendly name.

任务ID是按需分配的,不一定代表 创建任务实例的顺序

Task IDs are assigned on-demand and do not necessarily represent the order in the which Task instances were created

看看内置的Visual Studio 2010并行调试功能,也许您会发现其他方法:

Take a look at the built in Visual Studio 2010 Parallel Debugging features, perhaps you'll find an other approach: Walkthrough: Debugging a Parallel Application

并行任务窗口:

对于每个正在运行的任务,您可以读取其ID,该ID由 同名属性,运行该属性的线程的ID和名称, 位置(将鼠标悬停在该位置上会显示一个具有整个 调用堆栈).另外,在任务"列下,您可以看到 被传递给任务;换句话说,就是起点

For each running Task, you can read its ID, which is returned by the same-named property, the ID and name of the thread that runs it, its location (hovering over that displays a tooltip that has the whole call stack). Also, under the Task column, you can see the method that was passed into the task; in other words, the starting point

这篇关于如何命名运行任务的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆