Queue resolution for high concurrency logging
Queue resolution for high concurrency logging
In the case of high concurrency, there are a number of problems that usually do not occur will cause the user to wait, the following we use the log record as an example to illustrate a solution-queue.
Create a tool class: Logcommon as follows:
Namespace Heima8web.common
{
public class Logcommon
{
public static queue<string> Logqueue = new queue<string> (); Instantiate a queue
Static Logcommon ()//log writes to the file are implemented in the static constructor of the class, so that this method is called automatically when the queue is called
{
String strFileName = HttpContext.Current.Request.MapPath ("/app_data/log/" + DateTime.Now.ToString ("yyyy-mm-dd") + ". TXT "); Get the file path outside of the newly opened thread (each request corresponds to a thread, to the new thread, it will not get to the current context)
Open Line Pool Write log
ThreadPool.QueueUserWorkItem (A =
{
while (true)
{
String ex = string. Empty;
Lock ("Itcast-dotnet-aspnet-glable-loglock")
{
if (Logqueue.count > 0)//If there is data in the queue, send it out of the queue
{
ex = Logqueue.dequeue ();
}
Else
{
Thread.Sleep (30); If there is no data, let the thread sleep for 30 milliseconds before going to the next round of loops
Continue
}
}
Create a stream, write the log to a file
using (FileStream fs = new FileStream (strFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter writer = new StreamWriter (Fs,encoding.default))
{
Writer. Write (ex. ToString ());
}
}
}
});
}
public static void Writelog (String str)//method for writing logs to the queue
{
Lock ("Itcast-dotnet-aspnet-glable-loglock")
{
Logqueue.enqueue (str);
}
}
}
}
------------
Registering events in the Application_Error of the HttpApplication pipeline,
The following code is written in the Application_Error event of the global file:
protected void Application_Error (Object sender, EventArgs e)
{
Exception ex = Server.GetLastError (); Get the error message
Common.LogCommon.WriteLog (ex. ToString ()); Add the error message to the queue
}
=========================================================
Note: The static constructor Logcommon () is automatically called when the Common.LogCommon.WriteLog method is called because
Several principles of C # when using static constructors:
1. A static constructor is called before an instance of the class is created, so it is called before all instance constructors.
2. A static constructor is called before the first instance of the class is created.
3. A static constructor is called before a static field is referenced.
In a newly opened thread, it is not available in the current context.
Copy of the Log