EAP event-based Asynchronons Pattern

BackgroudWorker

最小实现

  1. class Program
  2. {
  3. static BackgroundWorker _bw = new BackgroundWorker();
  4. static void Main()
  5. {
  6. _bw.DoWork += bw_DoWork;
  7. _bw.RunWorkerAsync ("Message to worker");
  8. Console.ReadLine();
  9. }
  10. static void bw_DoWork (object sender, DoWorkEventArgs e)
  11. {
  12. // This is called on the worker thread
  13. Console.WriteLine (e.Argument); // writes "Message to worker"
  14. // Perform time-consuming task...
  15. }
  16. }

interrupt and abort

interrupt 不会终止线程,会让线程跳出一个try catch继续向下

cancellation Token 和 cancellation Source

lazy Initialization

  1. Expensive _expensive;
  2. public Expensive Expensive
  3. {
  4. get // Implement double-checked locking
  5. {
  6. LazyInitializer.EnsureInitialized (ref _expensive,
  7. () => new Expensive());
  8. return _expensive;
  9. }
  10. }
  1. Lazy<Expensive> _expensive = new Lazy<Expensive>
  2. (() => new Expensive(), true);
  3. 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);

  1. var localRandom = new ThreadLocal<Random>(() => new Random());
  2. Console.WriteLine (localRandom.Value.Next());

Timer

.net 自带4种timer

  1. The .NET Framework provides four timers. Two of these are general-purpose multithreaded timers:
  2. 两种多线程时钟:
  3. System.Threading.Timer
  4. System.Timers.Timer
  5. The other two are special-purpose single-threaded timers:
  6. 两种单线程时钟,专为界面使用:
  7. System.Windows.Forms.Timer (Windows Forms timer)
  8. 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.
更精确的时钟