Home > Enterprise >  Can I name each thread in this example?
Can I name each thread in this example?

Time:04-09

I want to create 10 threads with different names. Name should be a combination of name and id.ToString()

If I make a thread using Thread t = new Thread() then I know that I can do t.Name = name id.ToString();, but if I there is some way to do it with the code example below I would love to know it.

            string name = "Thread #";
            int id = 0;

            for (int i = 0; i < 10; i  )
            {
                new Thread(() =>
                {
                    for (int j = 0; j <= 100; j  )
                    {
                        //Do something
                    }

                }).Start();   
            }

CodePudding user response:

you could do

var t = new Thread(...);
t.Name = "Thread "   i;
t.Start();

But you should probably use the thread pool instead of creating explicit threads. In this specific case where you have a loop, you should probably use a Parallel.For. In general when you want to run something on a background thread you should use Task.Run, or in some cases Dataflow. When using the task pool you should not name threads, since the threads may be reused for other things. See How can I assign a name to a task in TPL for similar concept for tasks.

Using the thread pool reduces the overhead for running things in the background, and usually also provides interfaces that are easier to use.

CodePudding user response:

I just added Thread t = Thread.CurrentThread; and then I could do t.Name = $"Thread #{id}"; after. This is what it looks like in its' entirety:

            int tId = 0;
            for (int i = 0; i < 10; i  )
            {
                new Thread(() =>
                {
                    Thread t = Thread.CurrentThread; 
                    tId  ;
                    t.Name = $"Thread #{tId}";
                    Console.WriteLine($"{t.Name}");
                }).Start();
  • Related