The foundation is the top priority ~ Threadstaticquartz

Source: Internet
Author: User

The foundation is the top priority ~ Threadstaticquartz

Back to directory

ThreadStatic

ThreadStatic is a feature in C #. It can make your field valid in a thread, but you cannot control when the field will be recycled, that is to say, if the field of int32 is declared as ThreadStatic and the value you assign to it is 100, then what is it restored to the default value 0, which is unknown during development, we may only need to manually set it to 0, which is ugly, but there is no way. Who told us to use ThreadStatic? after it is declared as ThreadStatic, it has been proved that this field is static, but it is confined to a thread.

Quartz

Quartz is a job scheduling framework originating in java. It is widely used in various background data processing scenarios, such as statistical data, push data, and message data, it can greatly reduce the concurrency pressure on front-end servers, and there are many Quartz management interfaces. You can directly install nuget. The most well-known among these products should be CrystalQuartz, it can manage our JOB projects on the WEB interface!

Log System Lind. DDD. Logger

Logger is a log component of the Lind framework. It is the lowest-layer component and is the basis of other components. It is also used in other business systems. In one Quartz component, A question raised when using Logger is how to automatically create a log directory based on the job so that each JOB has its own directory, which is necessary for log analysis.

Expected results

Two jobs used for testing

Public class Hello_Job: JobBase {protected override void ExcuteJob () {Console. writeLine ("Hello Job method:" + Thread. currentThread. managedThreadId); Lind. DDD. logger. loggerFactory. instance. logger_Info ("Hello Job log! ") ;}} Public class Hi_Job: Lind. DDD. QuartzJob. JobBase {protected override void ExcuteJob () {Console. WriteLine (" Hi Job! "+ Thread. CurrentThread. ManagedThreadId); Lind. DDD. Logger. LoggerFactory. Instance. Logger_Info (" Hi Job! ");}}

JobBase is used to exist the base classes of all jobs. It mainly has its own Abstract methods and IJob interface methods. The abstract methods are implemented by the word class Job itself, the IJob method is called by the Quartz framework and the abstract method content is called by itself in the method. The Code is as follows:

[DisallowConcurrentExecution ()] public abstract class JobBase: IJob {# region IJob member /// <summary> // Job master method /// </summary> /// <param name = "context"> </param> public void Execute (IJobExecutionContext context) {Lind. DDD. logger. loggerFactory. instance. setPath (this. getType (). name); ExcuteJob (); Console. writeLine (DateTime. now. toString () + "{0} This Job starts execution", context. jobDetail. key. name) ;}# endregion /// <summary> // The specific class of the Job to implement its own logic // </summary> protected abstract void ExcuteJob ();}

ThreadStatic is used for fields in the log component.

Log files are stored in folders by ThreadStatic. The code is mainly as follows:

/// <Summary> /// each subclass executes the base class construction at the beginning, initializing the current Path. /// </summary> public LoggerBase () {FileUrl = Path. combine (AppDomain. currentDomain. baseDirectory, "LoggerDir") ;}/// <summary> /// log file address // The mvc solution address and website solution address are optimized, console program address // </summary> [ThreadStatic] static protected string FileUrl;
# Region ILogger member public void SetPath (string path) {if (! String. IsNullOrWhiteSpace (path) {FileUrl = FileUrl + "\" + path ;}# endregion

For the FileLogger file log implementation class, what it needs to do is, after writing the file streamTo assign a new value to the FileUrl field, because we do not know when the string will be cleared!

Lock (objLock) // prevents multi-threaded read/write conflicts {using (System. IO. streamWriter srFile = new System. IO. streamWriter (filePath, true) {srFile. writeLine (string. format ("{0} {1} {2}", DateTime. now. toString (). padRight (20), ("[ThreadID:" + Thread. currentThread. managedThreadId. toString () + "]"). padRight (14), message); srFile. close (); srFile. dispose () ;}/// clear the current Path FileUrl = Path. combine (AppDomain. currentDomain. baseDirectory, "LoggerDir ");

I have been searching for the above problem for a long time, because I can't find the reason why the test fails. I finally thought of the Declaration CYCLE OF THE ThreadStatic feature, which is the root cause!

We suggest you take a look at "the life and death of objects" in C #.

Back to directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.