Document directory
The code detection technology we will analyze next is tracking. In a multi-threaded application, this technology is very important. When multiple tasks have been started, you can track the behavior of one thread and the impact between each thread. We will see later that it is unrealistic to use the debugger in this case .. NET Framework provides many useful classes to help developers easily implement tracking functions. Let's take a look at the trace class in the System. Diagnostics namespace provided by. NET Framework.
1. Trace: this class has many static methods for writing messages to a listener. By default,. the debug output window in. NET will be used as a listener. Because a listener set is used, you can add different listeners, such as text listeners or Windows event log listeners.
2. Debug: The methods of this class are the same as those of the Trace class, and information is written to a listener application. The biggest difference between the two classes is that Trace is used for the running stage and Debug is used for the development stage.
3. BooleanSwitch: This class allows us to define a switch to enable/disable tracing messages.
4. TraceSwitch: This class provides four different trace levels to help developers choose to send different levels of messages to listeners.
Trace class
In this section, we will analyze several methods that are most frequently used in the Trace class. These methods are encapsulated by. NET Framework and provided to us. The Trace class is located in the System. Diagnostics namespace and provides many static methods to send messages to the listener.
The following table lists some static methods provided by the Trace class:
The default behavior of these methods depends on the selected listener program. For example, when the default listener is used, the Assert () method displays a message box.
Default listener program
The Trace class provides a set of listeners that allow us to add a new listener program. When no new listener object is added to the listener set, the Trace class uses the default listener program: debug output form. This form is provided by Visual Studio. net ide during debugging. Let's look at a simple example, TraceExample:
/*************************************/* Copyright (c) 2012 Daniel Dong * * Author:Daniel Dong * Blog: www.cnblogs.com/danielWise * Email: guofoo@163.com * */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;namespace TraceExample{ class Program { static void Main(string[] args) { Trace.WriteLine("Enter Main()"); for (int i = 0; i < 6; i++) { Trace.WriteLine(i); } Trace.WriteLine("Exiting from Main()"); } }}
This code is really simple. When you enter and exit the Main () method, It outputs debugging information and accumulates variable values in the loop. In the next section, you can see how the Visual Studio. NET output listener displays information:
The Trace class also provides two useful methods to Assert error prompts: Assert () and Fail (). the former allows developers to check whether the conditions passed in as parameters meet and write a message to the listener when the conditions are not met. The latter will write a message to the listener every time a failure occurs. When there are no other listener objects in the listener set, the Assert () method displays a message dialog box to provide the user's asserted failure. The following code snippet, TraceAssert. cs, can be tested when the SQL Server service is deliberately stopped and a connection error is thrown:
/*************************************/* Copyright (c) 2012 Daniel Dong * * Author:Daniel Dong * Blog: www.cnblogs.com/danielWise * Email: guofoo@163.com * */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Threading;using System.Data.SqlClient;namespace TraceExample{ class Program { [STAThread] static void Main(string[] args) { //Create a thread Thread t = new Thread(new ThreadStart(DBThread)); //Start the thread t.Start(); } private static void DBThread() { //Create a connection object SqlConnection dbConn = new SqlConnection(@"Data Source=DANIELFORWARD\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"); //Create a command object to execute a SQL statement SqlCommand dbComm = new SqlCommand("SELECT * FROM Region", dbConn); SqlDataReader dr = null; Trace.WriteLine(DateTime.Now + "- Execute SQL statement"); try { //Open the connection to the database dbConn.Open(); //Assert that the connection opened Trace.Assert(dbConn.State == System.Data.ConnectionState.Open, "Error", "Connection failed..."); //Execute the SQL statement dr = dbComm.ExecuteReader(System.Data.CommandBehavior.CloseConnection); //Assert that the statement executed OK Trace.Assert(dr != null, "Error", "The SqlDataReader is null."); while (dr.Read()) { //Reading records Trace.WriteLine(dr[0].ToString()); } } catch (Exception ex) { //Log the error to the Trace application Trace.Fail("An error occured in database access, details: " + ex.Message); } finally { if (!dr.IsClosed && dr != null) { dr.Close(); } } } }}
In the Main () method, a new thread is created and started. The new thread runs the code in DBThread. The Code simply connects to the SQL Server's Northwind database and collects all data from the Region table. If SQL Server is unavailable, the following asserted failure form is displayed during code execution.
The code that triggers an exception assertion is:
Trace.Assert(dbConn.State == System.Data.ConnectionState.Open, "Error", "Connection failed...");
You can see that the first parameter checks whether the connection status is enabled. When the connection is not enabled, it is set to false, and an asserted failure is displayed. You will learn from the subsequent sections of this chapter that you can also disable message tracing using the configuration file. In this way, you can decide whether to display the asserted message at runtime.
Transferred from blog garden ---- DanielWise