EAP event-based Asynchronons Pattern
BackgroudWorker
最小实现
class Program{static BackgroundWorker _bw = new BackgroundWorker();static void Main(){_bw.DoWork += bw_DoWork;_bw.RunWorkerAsync ("Message to worker");Console.ReadLine();}static void bw_DoWork (object sender, DoWorkEventArgs e){// This is called on the worker threadConsole.WriteLine (e.Argument); // writes "Message to worker"// Perform time-consuming task...}}
interrupt and abort
interrupt 不会终止线程,会让线程跳出一个try catch继续向下
cancellation Token 和 cancellation Source
lazy Initialization
Expensive _expensive;public Expensive Expensive{get // Implement double-checked locking{LazyInitializer.EnsureInitialized (ref _expensive,() => new Expensive());return _expensive;}}
Lazy<Expensive> _expensive = new Lazy<Expensive>(() => new Expensive(), true);public Expensive Expensive { get { return _expensive.Value; } }
Thread local
Unfortunately, [ThreadStatic] doesn’t work with instance fields (it simply does nothing); nor does it play well with field initializers — they execute only once on the thread that’s running when the static constructor executes. If you need to work with instance fields — or start with a nondefault value — ThreadLocal<T> provides a better option.
Here’s how to create a ThreadLocal with a default value of 3 for each thread:
static ThreadLocal _x = new ThreadLocal (() => 3);
var localRandom = new ThreadLocal<Random>(() => new Random());Console.WriteLine (localRandom.Value.Next());
Timer
.net 自带4种timer
The .NET Framework provides four timers. Two of these are general-purpose multithreaded timers:两种多线程时钟:System.Threading.TimerSystem.Timers.TimerThe other two are special-purpose single-threaded timers:两种单线程时钟,专为界面使用:System.Windows.Forms.Timer (Windows Forms timer)System.Windows.Threading.DispatcherTimer (WPF timer)
The precision of multithreaded timers depends on the operating system, and is typically in the 10–20 ms region. If you need greater precision, you can use native interop and call the Windows multimedia timer. This has precision down to 1 ms and it is defined in winmm.dll. First call timeBeginPeriod to inform the operating system that you need high timing precision, and then call timeSetEvent to start a multimedia timer. When you’re done, call timeKillEvent to stop the timer and timeEndPeriod to inform the OS that you no longer need high timing precision. You can find complete examples on the Internet that use the multimedia timer by searching for the keywords dllimport winmm.dll timesetevent.
更精确的时钟
