添加线程名称

时间:2013-11-13 15:22:20

标签: c# multithreading

我有一个申请。在调试过程中,我将重要信息记录到文件或交互界面。

以下是示例: demo

您会看到第一行日志信息没有线程名称。我想添加一个名字。但在哪里?

    public static void Start()
    {
        lock (SyncVar)
        {
            if (State == State.Stopped)
            {
                s_State = State.Starting;
                ThreadStart ts = new ThreadStart(MainCode);
                s_MainCodeThread = new Thread(ts);
                s_MainCodeThread.Name = "IvrApplication";
                s_MainCodeThread.Start();
                Log.Write("IvrApplication Starting...");
            }

和....

    public static void MainCode()
    {

        try
        {
            s_WorkingFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Log.Write("IvrApplication::MainCode() Starting...");

            // Start Other Threads...
            try
            {

对于Log,我们有

    private static Log s_Log;
    public static Log Log
    {
        get { return s_Log; }
    }

实际上Log来自dll

这是部分元数据。

namespace VoiceElements.Common
{
   public class Log
   {
       [ThreadStatic]
       public static string Identifier1;
       [ThreadStatic]
       public static string Identifier2;
       public int LogLevel;

       public Log(string logname);

       public bool AlwaysExpanded { get; set; }

       public event MessageLogged MessageLogged;

       public void CloseLog();
       public void Write(string LogEntry);

3 个答案:

答案 0 :(得分:4)

您只需要命名当前线程:

Thread.CurrentThread.Name = "myThread";

答案 1 :(得分:3)

应用程序的默认线程输出第一条日志消息。你应该能够设置:

Thread.CurrentThread.Name = "SomeName";

请务必在Log.Write("IvrApplication Starting...");之前拨打电话。

答案 2 :(得分:0)

您应该重命名执行MainCode方法的线程:

public static void MainCode()
{
    //SET A NAME HERE
    Thread.CurrentThread.Name = "Main thread"

    try
    {
        s_WorkingFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

        Log.Write("IvrApplication::MainCode() Starting...");

        // Start Other Threads...
        try
        {