0

My goal is to give the thread executing the task a name e.g. "WorkerForXY". But I don't want to name the thread inside of the task.

What is working but I don't want:

Task.Factory.StartNew(() =>
    {
       Thread.CurrentThread.Name = $"WorkerFor{taskName}";
       // some code
    }, TaskCreationOptions.LongRunning);

What I want to do:

var task = Task.Factory.StartNew(() =>
    {
       // some code
    }, TaskCreationOptions.LongRunning);
task.GetAssignedWorkerThreadIfAvailable().Name = $"WorkerFor{taskName}";    // or something similar

I think there might be a solution because Visual Studio can create such a mapping: enter image description here

knp
  • 44
  • 7
  • Why do you need to assign a name to a thread? :) I had to identify threads in my application that want to communicate with the database to prevent simultaneous calls to the database. I use a Semaphore object, which I assign a name to. I can then open the existing Semaphore, and prevent or allow the task to proceed if the previous thread with this name has finished. Let me know if this sounds like your problem, and I can post the code. – Daniël J.M. Hoffman Aug 31 '21 at 11:43
  • 1
    @DaniëlHoffman Thanks for your suggestion, but I need the naming for advanced logging (logging of ThreadId, TaskId and if possible also a ThreadName) and debugging. For synchronization of tasks I don't need a name. – knp Aug 31 '21 at 11:55
  • 1
    The Thread ID you see in Thread Assignment is what is returned by `AppDomain.GetCurrentThreadId()`, which, as you can see, is deprecated in managed code (because of lightweight threads), in favor of ManagedThreadId. Nobody stops you from assigning the Task.Id to a `ConcurrentDictionary`, where the class object stores the information you may need. – Jimi Aug 31 '21 at 13:05
  • A task may or may not have a thread and it may have multiple. I don't think what you're trying to do is practical or realistic. – Enigmativity Aug 31 '21 at 23:07
  • Have you considered to use purpose built system like [Hangfire](https://www.hangfire.io/), [Quartz](https://www.quartz-scheduler.net/), [FluentScheduler](https://github.com/fluentscheduler/FluentScheduler), etc.? – Peter Csala Sep 01 '21 at 07:12

1 Answers1

0

the task conception is an abstraction over "low level" threading conception (see more https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl), so trying getting or setting thread properties through the Task instance is not an appropriate decision (you can look through that question to go dipper How to get the reference of TPL task's thread in C#?)

my suggestion would be just to pass the name of the task as input param, especially if it's only for logging reason.

Polina
  • 23
  • 4