Tobia
Tobia

Reputation: 9506

C# System.Timers.Timer how to name its thread

This is my main method:

   public static void main(){
        var timer1=createDebounceTimer("TIMER1");
        var timer2=createDebounceTimer("TIMER2");
    }

This is my timer build code:

    private System.Timers.Timer createDebounceTimer(string threadName){
        var debounceTimer = new System.Timers.Timer(debounce * 1000);
        debounceTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        debounceTimer.AutoReset = false;
        //here I need to name the timer with threadName var
        return debounceTimer;
    }

and this is a simple elapse event:

    private void OnTimedEvent(object source, ElapsedEventArgs e)
       log.Info("My log system need the name of my thread");
    }

Question 1:

How to name the thread of the timer? I need this for logging purposes, in detail I would like to name the thread of the Elapsed event.

Question 2:

Can I be sure that there will be one dedicated thread per timer in case of multiple timer creation?

Upvotes: 0

Views: 1604

Answers (1)

Zaxxon
Zaxxon

Reputation: 667

Was wondering on this as well. Not sure how this stands up, but why not do something like this:

private void OnTimedEvent(object source, ElapsedEventArgs e)
   System.Threading.Thread.CurrentThread.Name = "CustomThreadName-" + System.Threading.Thread.CurrentThread.ManagedThreadId;
   log.Info("My log system need the name of my thread");
}

Log4Net will faithfully display "CustomThreadName-..." in the logs when using '%thread' in conversionPattern. The ManagedThreadId will at least give you uniqueness in your logs.

Upvotes: 2

Related Questions