C # review tips,
C # review tips
June 22, 2016
Main Attribute & Threads attributes and Threads
1. Conditional Attribute condition attributes
# Define debug // preprocessor directiveclass C {[Conditional ("debug")] // only possible for void methodsstatic void Assert (bool OK, string errorMsg) {if (! OK) {Console. writeString (errorMsg); System. environment. exit (0) ;}} static void Main (string [] arg) {Assert (arg. length> 0, "no arguments specified"); Assert (arg [0] = "... "," invalid argument ");...}}
Assertions are called only if debug is defined.
Assert is only called, if debug was defined.
It can also be used to control the trace output.
Also useful for controlling trace output.
2. Serialization
3. AttributeUsage
4. threads
// Assume there is a method void M () {} Thread t = new Thread (M); t. Start (); // Thread execution
5. Type
public sealed class Thread {public static Thread CurrentThread { get; } // static properties and methodspublic static void Sleep(int milliSeconds) {...}...public Thread(ThreadStart startMethod) {...} // thread creationpublic string Name { get; set; } // propertiespublic ThreadPriority Priority { get; set; }public ThreadState ThreadState { get; }public bool IsAlive { get; }public bool IsBackground { get; set; }...public void Start() {...} // methodspublic void Suspend() {...}public void Resume() {...}public void Join() {...} // t.Join(): caller waits for t to diepublic void Abort() {...} // throws ThreadAbortExceptionpublic void Interrupt() {...} // callable in WaitSleepState...}public delegate void ThreadStart(); // parameterless void methodpublic enum ThreadPriority {Normal, AboveNormal, BelowNormal, Highest, Lowest}public enum ThreadState {Unstarted, Running, Suspended, Stopped, Aborted, ...}
Example:
using System;using System.Threading;class Printer {char ch;int sleepTime;public Printer(char c, int t) {ch = c; sleepTime = t;}public void Print() {for (int i = 0; i < 100; i++) {Console.Write(ch);Thread.Sleep(sleepTime); } }}class Test {static void Main() {Printer a = new Printer('.', 10);Printer b = new Printer('*', 100);new Thread(a.Print).Start();new Thread(b.Print).Start(); }}
6. Differences from Java
7. thread status and mutual conversion
Using System; using System. threading; class Test {static void P () {for (int I = 0; I <20; I ++) {Console. write ('-'); Thread. sleep (100) ;}} static void Main () {Thread t = new Thread (P); Console. write ("start"); t. start (); t. join (); // waits until t has finishedConsole. writeLine ("end") ;}/// Output // start -------------------- end
using System; using System.Threading;class Test {static void P() {try {try {try {while (true) ; } catch (ThreadAbortException) { Console.WriteLine("-- inner aborted"); } } catch (ThreadAbortException) { Console.WriteLine("-- outer aborted"); } } finally { Console.WriteLine("-- finally"); }}static void Main(string[] arg) {Thread t = new Thread(P);t.Start(); Thread.Sleep(0);t.Abort(); t.Join(); Console.WriteLine("done"); }}/*Output-- inner aborted-- outer aborted-- finallydone*/
8. mutex Mutual Exclusion
Only one thread can grasp the lock at a time. The lock cannot be called by other threads until it is released.
Example:
class Account { // this class is a monitorlong val = 0;public void Deposit(long x) {lock (this) { val += x; } // only 1 thread at a time may execute this statement}public void Withdraw(long x) {lock (this) { val -= x; } }}
The lock can be applied to any type:
Object semaphore = new object ();
...
Lock (semaphore) {... critical region ...}
9. Wait and Pulse
Monitor. wait (lockedVar); // roughly equal to wait () in Java (in Java lockedVar is always this) Monitor. pulse (lockedVar); // roughly equal to notify () in JavaMonitor. pulseAll (lockedVar); // roughly equal to policyall () in Java
Example:
PulseAll (v) wakes up the V of all the waiting threads, but only one of them is allowed to continue. Other threads must wait until the previous one releases the lock. Then, the next thread may be executed.
PulseAll (v) wakes up all threads that wait for v, but only one of them is allowed to continue. the others must wait until the previous one has released the lock. then the next thread may enter the critical region.
Example: