. NET technology FAQ (11)-class library

Source: Internet
Author: User
Tags export class thread stop

11. Class Library
File I/O 11.1
11.1.1 how to read text files?
First, use the system. Io. filestream object to open the file:
Filestream FS = new filestream (@ "C:/test.txt", filemode. Open, fileaccess. Read );
Filestream inherits from stream, so you can use a streamreader object to wrap filestream objects. This provides a good interface for stream processing in one row and one row:
Streamreader sr = new streamreader (FS );
String curline;
While (curline = Sr. Readline ())! = NULL)
Console. writeline (curline );
Close the streamreader object:
Sr. Close ();
Note that close () is automatically called on the underlying Stream object, so fs. Close () does not need to be executed explicitly ().
 
11.1.2 how to write text files?
Similar to the example of reading a file, you only need to replace streamreader with streamwriter.
 
11.1.3 how do I read and write binary files?
Similar to text files, you only need to use binaryreader/writer objects instead of streamreader/writer to wrap filestream objects.
 
11.1.4 how to delete an object?
Use the static Delete () method on the system. Io. File object ():
File. Delete (@ "C:/test.txt ");
 
11.2 Text Processing
11.2.1 do I support regular expressions?
Yes. Use the system. Text. regularexpressions. RegEx class. For example, the following code updates the title of an HTML file:
Filestream FS = new filestream ("test.htm", filemode. Open, fileaccess. Read );
Streamreader sr = new streamreader (FS );

RegEx r = new RegEx ("<title> (. *) </title> ");
String S;
While (S = Sr. Readline ())! = NULL)
{
If (R. ismatch (s ))
S = R. Replace (S, "<title> New and improved $ {1} </title> ");
Console. writeline (s );
}
 
11.3 Internet
11.3.1 how do I download a webpage?
First, use the system. net. webrequestfactory class to obtain a webrequest object:
Webrequest request = webrequestfactory. Create ("http: // localhost ");
Then the request is answered:
Webresponse response = request. getresponse ();
The getresponse method is blocked until the download is complete. Then you can access the response stream as follows:
Stream S = response. getresponsestream ();

// Output the downloaded stream to the console
Streamreader sr = new streamreader (s );
String line;
While (line = Sr. Readline ())! = NULL)
Console. writeline (line );
Note that the webrequest and webreponse objects are backward compatible with httpwebrequest and httpwebreponse objects, which are used to access HTTP-related functions.
 
11.3.2 how do I use a proxy )?
Two methods-this can affect all Web requests:
System. net. globalproxyselection. Select = new defaultcontrolobject ("proxyname", 80 );
In addition, to set proxy services for specific Web requests, do the following:
Proxydata = new proxydata ();
Proxydata. hostname = "proxyname ";
Proxydata. Port = 80;
Proxydata. overrideselectproxy = true;

Httpwebrequest request = (httpwebrequest) webrequestfactory. Create ("http: // localhost ");
Request. Proxy = proxydata;
 
11.4 XML
11.4.1 does Dom support?
Yes. Take a look at the following example XML document:
<People>
<Person> Fred </person>
<Person> Bill </person>
</People>
You can process this document as follows:
Xmldocument Doc = new xmldocument ();
Doc. Load ("test. xml ");

Xmlnode root = Doc. documentelement;

Foreach (xmlnode personelement in root. childnodes)
Console. writeline (personelement. firstchild. value. tostring ());
Output:
Fred
Bill
 
11.4.2 does it support sax?
No. As a replacement, a new xmlreader/xmlwriter API is provided. Like sax, It is stream-based, but it uses the "pull" model instead of the "push" model of sax. This is an example:
Xmltextreader reader = new xmltextreader ("test. xml ");

While (reader. Read ())
{
If (reader. nodetype = xmlnodetype. Element & reader. Name = "person ")
{
Reader. Read (); // skip to the Child text
Console. writeline (reader. value );
}
}
 
11.4.3 does it support XPath?
Yes, via the xmlnavigator class (documentnavigator is exported from xmlnavigator ):
Xmldocument Doc = new xmldocument ();
Doc. Load ("test. xml ");

Documentnavigator nav = new documentnavigator (DOC );
Nav. movetodocument ();

Nav. Select ("Descendant: People/person ");

While (NAV. movetonextselected ())
{
Nav. movetofirstchild ();
Console. writeline ("{0}", Nav. value );
}
 
Thread 11.5
11.5.1 is multithreading supported?
Yes, it has extensive support for multithreading. The system can generate new threads and provide a thread pool that can be used by applications.
 
11.5.2 how to generate a thread?
Create an instance of the system. Threading. thread object and pass the threadstart example to be executed in the new thread to it. For example:
Class mythread
{
Public mythread (string initdata)
{
M_data = initdata;
M_thread = new thread (New threadstart (threadmain ));
M_thread.start ();
}

// Threadmain () is executed on the new thread.
Private void threadmain ()
{
Console. writeline (m_data );
}

Public void waituntilfinished ()
{
M_thread.join ();
}

Private thread m_thread;
Private string m_data;
}
Here, creating an instance of mythread is enough to generate a thread and execute the mythread. threadmain () method:
Mythread T = new mythread ("Hello, world .");
T. waituntilfinished ();
 
11.5.3 how do I stop a thread?
There are several methods. First, you can use your communication mechanism to tell the threadstart method to end. In addition, the thread class has built-in support for command thread stop. The two basic methods are thread. Interrupt () and thread. Abort (). The former throws a threadinterruptedexception and then enters the waitjoinsleep state. In other words, thread. Interrupt is a courtesy method that requests the thread to stop itself when it no longer performs any useful work. Correspondingly, thread. Abort () throws a threadabortexception regardless of what the thread is doing. Moreover, threadabortexception cannot be captured as usual (even if the end method of threadstart will be executed ). Thread. Abort () is an uncommon method.
 
11.5.4 how to use the thread pool?
Pass an instance of waitcallback to the threadpool. queueuserworkitem () method:
Class CAPP
{
Static void main ()
{
String S = "Hello, world ";
Threadpool. queueuserworkitem (New waitcallback (dowork), S );

Thread. Sleep (1000); // give time for work item to be executed
}

// Dowork is executed on a thread from the thread pool.
Static void dowork (object state)
{
Console. writeline (State );
}
}
 
11.5.5 how do I know when my thread pool work project will be completed?
There is no way to ask such information about the thread pool. You must place code in the waitcallback method to send a signal to indicate that it has been completed. Events here are also very useful.
 
11.5.6 how to prevent concurrent access to data?
Each object has a concurrent lock associated with it (the criticized part ). The system. Threading. Monitor. Enter/exit method is used to obtain and release locks. For example, the following class instance only allows one thread to enter the method F () at the same time ():
Class C
{
Public void F ()
{
Try
{
Monitor. Enter (this );
...
}
Finally
{
Monitor. Exit (this );
}
}
}
C # The keyword 'lock' provides a simple form of the above Code:
Class C
{
Public void F ()
{
Lock (this)
{
...
}
}
}
Note that calling monitor. Enter (myobject) does not mean that all access to myobject is serialized. It means that the synchronization lock associated with the myobject is requested, and no other thread can request the lock before the monitor. Exit (o) is called. In other words, the following class is functionally equivalent to the class given above:
Class C
{
Public void F ()
{
Lock (m_object)
{
...
}
}

Private m_object = new object ();
}
 
11.6 tracking
11.6.1 is there any built-in tracking/log support?
Yes, in the system. Diagnostics namespace. There are two main classes for processing trace-Debug and trace. They work in a similar way-the difference is that the tracing in the debug class can only work in the code generated with the debug flag, the trace in the trace class can only work in the code that indicates the trace tag generation. Typically, this means that you should use system when you want to be able to track both the debug and release versions. diagnostics. trace. writeline, and you want to use system only when tracing is available in the debug version. diagnostics. debug. writeline.
 
11.6.2 can I redirect trace output to a file?
Yes. Both the debug class and the trace class have a listeners attribute, which collects the output generated by Debug. writeline or trace. writeline respectively. By default, listeners has only one collection slot, which is an instance of the defaulttracelistener class. It sends the output to the outputdebugstring () function of Win32 and the system. Diagnostics. Debugger. Log () method. This is useful during debugging, but it is more appropriate to redirect the output to a file if you try to track a problem from the customer site. Fortunately, the textwritertracelistener class is provided for this purpose.
Here is how textwritertracelistener redirects the trace output to a file:
Trace. listeners. Clear ();
Filestream FS = new filestream (@ "C:/log.txt", filemode. Create, fileaccess. Write );
Trace. listeners. Add (New textwritertracelistener (FS ));

Trace. writeline (@ "This will be writen to C:/log.txt! ");
Note that the default listener is removed by using trace. listeners. Clear. Otherwise, the output is generated in both the file and outputdebugstring. Generally, you do not want this because outputdebugstring () causes high performance overhead.
 
11.6.3 can I customize the tracing output?
Yes. You can write your own tracelistener export class and redirect all the output to it. Here is a simple example: it exports from textwritertracelistener (and then has built-in support for writing files) and adds time information and thread ID on each output line:
Class mylistener: textwritertracelistener
{
Public mylistener (Stream S): Base (s)
{
}

Public override void writeline (string S)
{
Writer. writeline ("{0: D8} [{1: D4}] {2 }",
Environment. tickcount-m_starttickcount,
Appdomain. getcurrentthreadid (),
S );
}

Protected int m_starttickcount = environment. tickcount;
}
(Note that this implementation is incomplete-for example, the tracelistener. Write method is not overwritten .)
The beauty of this method is that, to trace. after mylistener is added to listener, all trace. all calls to writeline () are directed to mylistener, including calls from referenced components that do not know anything about mylistener.
 
 
Microsoft also released the. NET Framework FAQ, which is similar to this article. You can find more authoritative answers to many questions here.
Robert scoble edited an easily understandable online list.

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.