1.  
  2. //#define NET35
  3. namespace TestConsoleApplication
  4. {
  5. using System;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Microshaoft;
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. Console.WriteLine("Begin ...");
  15. Random r = new Random();
  16. int sleep = 100;
  17. int iterations = 2000;
  18. int maxDegreeOfParallelism = 8; // Environment.ProcessorCount;
  19. var performanceCountersCategoryName = "Microshaoft EasyPerformanceCounters Category";
  20. var performanceCountersCategoryInstanceName = string.Format
  21. (
  22. "{2}{0}{3}{1}{4}"
  23. , ": "
  24. , " @ "
  25. , ""
  26. , ""
  27. , Process.GetCurrentProcess().ProcessName
  28. );
  29. //EasyPerformanceCountersHelper 调用示例
  30. //调用 EasyPerformanceCountersHelper.AttachPerformanceCountersCategoryInstance 可加载性能计数器
  31. EasyPerformanceCountersHelper.AttachPerformanceCountersCategoryInstance
  32. (
  33. performanceCountersCategoryName
  34. , performanceCountersCategoryInstanceName + "-1"
  35. );
  36. var enableCounters = MultiPerformanceCountersTypeFlags.ProcessCounter
  37. | MultiPerformanceCountersTypeFlags.ProcessedAverageTimerCounter
  38. | MultiPerformanceCountersTypeFlags.ProcessedCounter
  39. | MultiPerformanceCountersTypeFlags.ProcessedRateOfCountsPerSecondCounter
  40. | MultiPerformanceCountersTypeFlags.ProcessingCounter;
  41. //EasyPerformanceCountersHelper 可以直接使用 比如 用于 ASP.NET page_load 程序中代码中
  42. EasyPerformanceCountersHelper.CountPerformance
  43. (
  44. enableCounters
  45. , performanceCountersCategoryName
  46. , performanceCountersCategoryInstanceName + "-1"
  47. , null
  48. , () =>
  49. {
  50. //需要性能计数器的代码段
  51. //begin ==============================================
  52. var x = r.Next(0, 10) * sleep;
  53. Thread.Sleep(x);
  54. //end ================================================
  55. }
  56. , null
  57. );
  58. Parallel.For
  59. (
  60. 0
  61. , 99
  62. , (x) =>
  63. {
  64. Stopwatch stopwatch =
  65. EasyPerformanceCountersHelper.CountPerformanceBegin
  66. (
  67. enableCounters
  68. , performanceCountersCategoryName
  69. , performanceCountersCategoryInstanceName + "-1"
  70. );
  71. //需要性能计数器的代码段
  72. //begin ==============================================
  73. var xx = r.Next(0, 10) * sleep;
  74. Thread.Sleep(xx);
  75. //end ================================================
  76. if (stopwatch != null)
  77. {
  78. EasyPerformanceCountersHelper.CountPerformanceEnd
  79. (
  80. enableCounters
  81. , performanceCountersCategoryName
  82. , performanceCountersCategoryInstanceName + "-1"
  83. , stopwatch
  84. );
  85. stopwatch = null;
  86. }
  87. }
  88. );
  89. //CodeTimerPerformance 调用示例
  90. //CodeTimerPerformance.AttachPerformanceCountersCategoryInstance 可加载性能计数器
  91. CodeTimerPerformance.AttachPerformanceCountersCategoryInstance
  92. (
  93. performanceCountersCategoryName
  94. , performanceCountersCategoryInstanceName + "-2"
  95. );
  96. enableCounters =
  97. MultiPerformanceCountersTypeFlags.ProcessCounter
  98. | MultiPerformanceCountersTypeFlags.ProcessingCounter
  99. | MultiPerformanceCountersTypeFlags.ProcessedCounter
  100. | MultiPerformanceCountersTypeFlags.ProcessedAverageTimerCounter
  101. | MultiPerformanceCountersTypeFlags.ProcessedRateOfCountsPerSecondCounter;
  102. //enableCounters = MultiPerformanceCountersTypeFlags.None;
  103. CodeTimerPerformance.ParallelTime
  104. (
  105. "ParallelTime1"
  106. , iterations
  107. , () =>
  108. {
  109. //需要性能计数器的代码段
  110. //begin ==============================================
  111. var x = r.Next(0, 10) * sleep;
  112. Thread.Sleep(x);
  113. //end ================================================
  114. }
  115. , maxDegreeOfParallelism
  116. , enableCounters
  117. , performanceCountersCategoryName
  118. , performanceCountersCategoryInstanceName + "-1"
  119. );
  120. CodeTimerPerformance.Time
  121. (
  122. "Time2"
  123. , iterations
  124. , () =>
  125. {
  126. //需要性能计数器的代码段
  127. //begin ==============================================
  128. var x = r.Next(0, 10) * sleep;
  129. Thread.Sleep(x);
  130. //end ================================================
  131. }
  132. //, maxDegreeOfParallelism
  133. , enableCounters
  134. , performanceCountersCategoryName
  135. , performanceCountersCategoryInstanceName + "-2"
  136. );
  137. Console.WriteLine("End ...");
  138. Console.ReadLine();
  139. }
  140. }
  141. }
  142. namespace Microshaoft
  143. {
  144. using System;
  145. using System.Diagnostics;
  146. using System.Runtime.InteropServices;
  147. using System.Threading;
  148. using System.Threading.Tasks;
  149. public static class CodeTimerPerformance
  150. {
  151. public static void Initialize()
  152. {
  153. Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
  154. Thread.CurrentThread.Priority = ThreadPriority.Highest;
  155. Time("", 1, () => { }, MultiPerformanceCountersTypeFlags.None, string.Empty, string.Empty);
  156. }
  157. public static void AttachPerformanceCountersCategoryInstance
  158. (
  159. string performanceCountersCategoryName
  160. , string performanceCountersCategoryInstanceName
  161. )
  162. {
  163. EasyPerformanceCountersHelper.AttachPerformanceCountersCategoryInstance
  164. (
  165. performanceCountersCategoryName
  166. , performanceCountersCategoryInstanceName
  167. );
  168. }
  169. public static void ParallelTime
  170. (
  171. string name
  172. , int iterations
  173. , Action actionOnce
  174. , int maxDegreeOfParallelism //= 1
  175. , MultiPerformanceCountersTypeFlags enablePerformanceCounters //= false
  176. , string performanceCountersCategoryName
  177. , string performanceCountersCategoryInstanceName
  178. )
  179. {
  180. // 1.
  181. ConsoleColor currentForeColor = Console.ForegroundColor;
  182. Console.ForegroundColor = ConsoleColor.Yellow;
  183. Console.WriteLine(name);
  184. // 2.
  185. GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
  186. int[] gcCounts = new int[GC.MaxGeneration + 1];
  187. for (int i = 0; i <= GC.MaxGeneration; i++)
  188. {
  189. gcCounts[i] = GC.CollectionCount(i);
  190. }
  191. IntPtr threadID = GetCurrentThreadId();
  192. Stopwatch watch = Stopwatch.StartNew();
  193. ulong cycleCount = GetCurrentThreadCycleCount();
  194. Parallel.For
  195. (
  196. 0
  197. , iterations
  198. , new ParallelOptions()
  199. {
  200. MaxDegreeOfParallelism = maxDegreeOfParallelism
  201. //, TaskScheduler = null
  202. }
  203. , (x) =>
  204. {
  205. EasyPerformanceCountersHelper.CountPerformance
  206. (
  207. enablePerformanceCounters
  208. , performanceCountersCategoryName
  209. , performanceCountersCategoryInstanceName
  210. , null
  211. , actionOnce
  212. , null
  213. );
  214. }
  215. );
  216. ulong cpuCycles = GetCurrentThreadCycleCount() - cycleCount;
  217. watch.Stop();
  218. //watch = null;
  219. // 4.
  220. Console.ForegroundColor = currentForeColor;
  221. Console.WriteLine
  222. (
  223. "{0}Time Elapsed:{0}{1}ms"
  224. , "\t"
  225. , watch.ElapsedMilliseconds.ToString("N0")
  226. );
  227. Console.WriteLine
  228. (
  229. "{0}CPU Cycles:{0}{1}"
  230. , "\t"
  231. , cpuCycles.ToString("N0")
  232. );
  233. // 5.
  234. for (int i = 0; i <= GC.MaxGeneration; i++)
  235. {
  236. int count = GC.CollectionCount(i) - gcCounts[i];
  237. Console.WriteLine
  238. (
  239. "{0}Gen{1}:{0}{0}{2}"
  240. , "\t"
  241. , i
  242. , count
  243. );
  244. }
  245. Console.WriteLine();
  246. }
  247. public static void Time
  248. (
  249. string name
  250. , int iterations
  251. , Action actionOnce
  252. , MultiPerformanceCountersTypeFlags enablePerformanceCounters //= false
  253. , string performanceCountersCategoryName
  254. , string performanceCountersCategoryInstanceName
  255. )
  256. {
  257. ParallelTime
  258. (
  259. name
  260. , iterations
  261. , actionOnce
  262. , 1
  263. , enablePerformanceCounters
  264. , performanceCountersCategoryName
  265. , performanceCountersCategoryInstanceName
  266. );
  267. }
  268. private static ulong GetThreadCycleCount(IntPtr threadID)
  269. {
  270. ulong cycleCount = 0;
  271. QueryThreadCycleTime(threadID, ref cycleCount);
  272. return cycleCount;
  273. }
  274. private static ulong GetCurrentThreadCycleCount()
  275. {
  276. IntPtr threadID = GetCurrentThread();
  277. return GetThreadCycleCount(threadID);
  278. }
  279. [DllImport("kernel32.dll")]
  280. [return: MarshalAs(UnmanagedType.Bool)]
  281. static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);
  282. [DllImport("kernel32.dll")]
  283. static extern IntPtr GetCurrentThread();
  284. [DllImport("kernel32.dll")]
  285. static extern IntPtr GetCurrentThreadId();
  286. }
  287. }
  288. namespace Microshaoft
  289. {
  290. using System;
  291. using System.Collections.Generic;
  292. using System.Diagnostics;
  293. //using System.Collections.Concurrent;
  294. public static class EasyPerformanceCountersHelper
  295. {
  296. private static Dictionary<string, CommonPerformanceCountersContainer> _dictionary = new Dictionary<string, CommonPerformanceCountersContainer>();
  297. public static void AttachPerformanceCountersCategoryInstance
  298. (
  299. string performanceCountersCategoryName
  300. , string performanceCountersCategoryInstanceName
  301. )
  302. {
  303. string key = string.Format
  304. (
  305. "{1}{0}{2}"
  306. , "-"
  307. , performanceCountersCategoryName
  308. , performanceCountersCategoryInstanceName
  309. );
  310. CommonPerformanceCountersContainer container = null;
  311. if (!_dictionary.TryGetValue(key, out container))
  312. {
  313. container = new CommonPerformanceCountersContainer();
  314. _dictionary.Add
  315. (
  316. key
  317. , container //new CommonPerformanceCountersContainer()
  318. );
  319. container.AttachPerformanceCountersToProperties(performanceCountersCategoryInstanceName, performanceCountersCategoryName);
  320. }
  321. }
  322. private static object _lockerObject = new object();
  323. public static Stopwatch CountPerformanceBegin
  324. (
  325. MultiPerformanceCountersTypeFlags enabledPerformanceCounters
  326. , string performanceCountersCategoryName
  327. , string performanceCountersCategoryInstanceName
  328. )
  329. {
  330. Stopwatch r = null;
  331. if (enabledPerformanceCounters != MultiPerformanceCountersTypeFlags.None)
  332. {
  333. string key = string.Format
  334. (
  335. "{1}{0}{2}"
  336. , "-"
  337. , performanceCountersCategoryName
  338. , performanceCountersCategoryInstanceName
  339. );
  340. CommonPerformanceCountersContainer container = null;
  341. if (!_dictionary.TryGetValue(key, out container))
  342. {
  343. lock (_lockerObject)
  344. {
  345. container = new CommonPerformanceCountersContainer();
  346. _dictionary.Add
  347. (
  348. key
  349. , new CommonPerformanceCountersContainer()
  350. );
  351. container.AttachPerformanceCountersToProperties
  352. (
  353. performanceCountersCategoryInstanceName
  354. , performanceCountersCategoryName
  355. );
  356. }
  357. }
  358. var enableProcessCounter =
  359. (
  360. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessCounter)
  361. != MultiPerformanceCountersTypeFlags.None
  362. );
  363. if (enableProcessCounter)
  364. {
  365. container.PrcocessPerformanceCounter.Increment();
  366. }
  367. var enableProcessingCounter =
  368. (
  369. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessingCounter)
  370. != MultiPerformanceCountersTypeFlags.None
  371. );
  372. if (enableProcessingCounter)
  373. {
  374. container.ProcessingPerformanceCounter.Increment();
  375. }
  376. var enableProcessedAverageTimerCounter =
  377. (
  378. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedAverageTimerCounter)
  379. != MultiPerformanceCountersTypeFlags.None
  380. );
  381. if (enableProcessedAverageTimerCounter)
  382. {
  383. r = Stopwatch.StartNew();
  384. }
  385. }
  386. return r;
  387. }
  388. public static void CountPerformanceEnd
  389. (
  390. MultiPerformanceCountersTypeFlags enabledPerformanceCounters
  391. , string performanceCountersCategoryName
  392. , string performanceCountersCategoryInstanceName
  393. , Stopwatch stopwatch
  394. )
  395. {
  396. string key = string.Format
  397. (
  398. "{1}{0}{2}"
  399. , "-"
  400. , performanceCountersCategoryName
  401. , performanceCountersCategoryInstanceName
  402. );
  403. CommonPerformanceCountersContainer container = null;
  404. if (!_dictionary.TryGetValue(key, out container))
  405. {
  406. return;
  407. }
  408. var enableProcessedAverageTimerCounter =
  409. (
  410. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedAverageTimerCounter)
  411. != MultiPerformanceCountersTypeFlags.None
  412. );
  413. if (enableProcessedAverageTimerCounter)
  414. {
  415. if (stopwatch != null)
  416. {
  417. PerformanceCounter performanceCounter = container.ProcessedAverageTimerPerformanceCounter;
  418. PerformanceCounter basePerformanceCounter = container.ProcessedAverageBasePerformanceCounter;
  419. stopwatch.Stop();
  420. performanceCounter.IncrementBy(stopwatch.ElapsedTicks);
  421. basePerformanceCounter.Increment();
  422. //stopwatch = null;
  423. }
  424. }
  425. var enableProcessingCounter =
  426. (
  427. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessingCounter)
  428. != MultiPerformanceCountersTypeFlags.None
  429. );
  430. if (enableProcessingCounter)
  431. {
  432. container.ProcessingPerformanceCounter.Decrement();
  433. }
  434. var enableProcessedPerformanceCounter =
  435. (
  436. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedCounter)
  437. != MultiPerformanceCountersTypeFlags.None
  438. );
  439. if (enableProcessedPerformanceCounter)
  440. {
  441. container.ProcessedPerformanceCounter.Increment();
  442. }
  443. var enableProcessedRateOfCountsPerSecondPerformanceCounter =
  444. (
  445. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedRateOfCountsPerSecondCounter)
  446. != MultiPerformanceCountersTypeFlags.None
  447. );
  448. if (enableProcessedRateOfCountsPerSecondPerformanceCounter)
  449. {
  450. container.ProcessedRateOfCountsPerSecondPerformanceCounter.Increment();
  451. }
  452. }
  453. public static void CountPerformance
  454. (
  455. MultiPerformanceCountersTypeFlags enabledPerformanceCounters
  456. , string performanceCountersCategoryName
  457. , string performanceCountersCategoryInstanceName
  458. , Action onBeforeCountPerformanceInnerProcessAction
  459. , Action onCountPerformanceInnerProcessAction
  460. , Action onAfterCountPerformanceInnerProcessAction
  461. )
  462. {
  463. if (enabledPerformanceCounters != MultiPerformanceCountersTypeFlags.None)
  464. {
  465. if (onCountPerformanceInnerProcessAction != null)
  466. {
  467. string key = string.Format
  468. (
  469. "{1}{0}{2}"
  470. , "-"
  471. , performanceCountersCategoryName
  472. , performanceCountersCategoryInstanceName
  473. );
  474. CommonPerformanceCountersContainer container = null;
  475. if (!_dictionary.TryGetValue(key, out container))
  476. {
  477. lock (_lockerObject)
  478. {
  479. container = new CommonPerformanceCountersContainer();
  480. _dictionary.Add
  481. (
  482. key
  483. , new CommonPerformanceCountersContainer()
  484. );
  485. container.AttachPerformanceCountersToProperties
  486. (
  487. performanceCountersCategoryInstanceName
  488. , performanceCountersCategoryName
  489. );
  490. }
  491. }
  492. var enableProcessCounter =
  493. (
  494. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessCounter)
  495. != MultiPerformanceCountersTypeFlags.None
  496. );
  497. if (enableProcessCounter)
  498. {
  499. container.PrcocessPerformanceCounter.Increment();
  500. }
  501. var enableProcessingCounter =
  502. (
  503. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessingCounter)
  504. != MultiPerformanceCountersTypeFlags.None
  505. );
  506. if (enableProcessingCounter)
  507. {
  508. container.ProcessingPerformanceCounter.Increment();
  509. }
  510. var enableProcessedAverageTimerCounter =
  511. (
  512. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedAverageTimerCounter)
  513. != MultiPerformanceCountersTypeFlags.None
  514. );
  515. try
  516. {
  517. container.ProcessedAverageTimerPerformanceCounter.ChangeAverageTimerCounterValueWithTryCatchExceptionFinally
  518. (
  519. enableProcessedAverageTimerCounter
  520. , container.ProcessedAverageBasePerformanceCounter
  521. , () =>
  522. {
  523. if (onCountPerformanceInnerProcessAction != null)
  524. {
  525. if (onBeforeCountPerformanceInnerProcessAction != null)
  526. {
  527. onBeforeCountPerformanceInnerProcessAction();
  528. }
  529. onCountPerformanceInnerProcessAction();
  530. if (onAfterCountPerformanceInnerProcessAction != null)
  531. {
  532. onAfterCountPerformanceInnerProcessAction();
  533. }
  534. }
  535. }
  536. , null
  537. , null
  538. );
  539. }
  540. catch (Exception e)
  541. {
  542. throw new Exception("ReThrow Exception On Caught Excepion", e);
  543. }
  544. finally
  545. {
  546. if (enableProcessingCounter)
  547. {
  548. container.ProcessingPerformanceCounter.Decrement();
  549. }
  550. var enableProcessedPerformanceCounter =
  551. (
  552. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedCounter)
  553. != MultiPerformanceCountersTypeFlags.None
  554. );
  555. if (enableProcessedPerformanceCounter)
  556. {
  557. container.ProcessedPerformanceCounter.Increment();
  558. }
  559. var enableProcessedRateOfCountsPerSecondPerformanceCounter =
  560. (
  561. (enabledPerformanceCounters & MultiPerformanceCountersTypeFlags.ProcessedRateOfCountsPerSecondCounter)
  562. != MultiPerformanceCountersTypeFlags.None
  563. );
  564. if (enableProcessedRateOfCountsPerSecondPerformanceCounter)
  565. {
  566. container.ProcessedRateOfCountsPerSecondPerformanceCounter.Increment();
  567. }
  568. }
  569. }
  570. }
  571. else
  572. {
  573. if (onCountPerformanceInnerProcessAction != null)
  574. {
  575. onCountPerformanceInnerProcessAction();
  576. }
  577. }
  578. }
  579. }
  580. }
  581. //=========================================================================================
  582. //=========================================================================================
  583. namespace Microshaoft
  584. {
  585. using System;
  586. using System.Diagnostics;
  587. public class CommonPerformanceCountersContainer
  588. {
  589. #region PerformanceCounters
  590. private PerformanceCounter _processPerformanceCounter;
  591. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.NumberOfItems64, CounterName = "01.接收处理笔数(笔)")]
  592. public PerformanceCounter PrcocessPerformanceCounter
  593. {
  594. private set
  595. {
  596. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _processPerformanceCounter, value, 2);
  597. }
  598. get
  599. {
  600. return _processPerformanceCounter;
  601. }
  602. }
  603. private PerformanceCounter _processingPerformanceCounter;
  604. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.NumberOfItems64, CounterName = "02.正在处理笔数(笔)")]
  605. public PerformanceCounter ProcessingPerformanceCounter
  606. {
  607. private set
  608. {
  609. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _processingPerformanceCounter, value, 2);
  610. }
  611. get
  612. {
  613. return _processingPerformanceCounter;
  614. }
  615. }
  616. private PerformanceCounter _processedPerformanceCounter;
  617. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.NumberOfItems64, CounterName = "03.完成处理笔数(笔)")]
  618. public PerformanceCounter ProcessedPerformanceCounter
  619. {
  620. private set
  621. {
  622. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _processedPerformanceCounter, value, 2);
  623. }
  624. get
  625. {
  626. return _processedPerformanceCounter;
  627. }
  628. }
  629. private PerformanceCounter _processedRateOfCountsPerSecondPerformanceCounter;
  630. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.RateOfCountsPerSecond64, CounterName = "04.每秒完成处理笔数(笔/秒)")]
  631. public PerformanceCounter ProcessedRateOfCountsPerSecondPerformanceCounter
  632. {
  633. private set
  634. {
  635. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _processedRateOfCountsPerSecondPerformanceCounter, value, 2);
  636. }
  637. get
  638. {
  639. return _processedRateOfCountsPerSecondPerformanceCounter;
  640. }
  641. }
  642. private PerformanceCounter _ProcessedAverageTimerPerformanceCounter;
  643. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.AverageTimer32, CounterName = "05.平均每笔处理耗时秒数(秒/笔)")]
  644. public PerformanceCounter ProcessedAverageTimerPerformanceCounter
  645. {
  646. private set
  647. {
  648. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _ProcessedAverageTimerPerformanceCounter, value, 2);
  649. }
  650. get
  651. {
  652. return _ProcessedAverageTimerPerformanceCounter;
  653. }
  654. }
  655. private PerformanceCounter _processedAverageBasePerformanceCounter;
  656. [PerformanceCounterDefinitionAttribute(CounterType = PerformanceCounterType.AverageBase)]
  657. public PerformanceCounter ProcessedAverageBasePerformanceCounter
  658. {
  659. private set
  660. {
  661. ReaderWriterLockSlimHelper.TryEnterWriterLockSlimWrite<PerformanceCounter>(ref _processedAverageBasePerformanceCounter, value, 2);
  662. }
  663. get
  664. {
  665. return _processedAverageBasePerformanceCounter;
  666. }
  667. }
  668. #endregion
  669. // indexer declaration
  670. public PerformanceCounter this[string name]
  671. {
  672. get
  673. {
  674. throw new NotImplementedException();
  675. //return null;
  676. }
  677. }
  678. //private bool _isAttachedPerformanceCounters = false;
  679. public void AttachPerformanceCountersToProperties
  680. (
  681. string instanceName
  682. , string categoryName
  683. )
  684. {
  685. var type = this.GetType();
  686. PerformanceCountersHelper.AttachPerformanceCountersToProperties<CommonPerformanceCountersContainer>(instanceName, categoryName, this);
  687. }
  688. }
  689. }
  690. namespace Microshaoft
  691. {
  692. using System;
  693. using System.Diagnostics;
  694. public static class PerformanceCounterExtensionMethodsManager
  695. {
  696. public static T ChangeCounterValueWithTryCatchExceptionFinally<T>
  697. (
  698. this PerformanceCounter performanceCounter
  699. , bool enabled
  700. , Func<PerformanceCounter, T> onCounterChangeProcessFunc //= null
  701. , Action<PerformanceCounter> onCounterChangedProcessAction //= null
  702. , Func<PerformanceCounter, Exception, bool> onCaughtExceptionProcessFunc //= null
  703. , Action<PerformanceCounter> onCaughtExceptionFinallyProcessAction //= null
  704. )
  705. {
  706. T r = default(T);
  707. if (enabled)
  708. {
  709. if (onCounterChangeProcessFunc != null)
  710. {
  711. var caughtException = false;
  712. try
  713. {
  714. r = onCounterChangeProcessFunc(performanceCounter);
  715. }
  716. catch (Exception e)
  717. {
  718. caughtException = true;
  719. var reThrow = true;
  720. if (onCaughtExceptionProcessFunc != null)
  721. {
  722. reThrow = onCaughtExceptionProcessFunc(performanceCounter, e);
  723. }
  724. if (reThrow)
  725. {
  726. throw new Exception("ReThrow Exception On Caught Excepion", e);
  727. }
  728. }
  729. finally
  730. {
  731. if (caughtException)
  732. {
  733. if (onCaughtExceptionFinallyProcessAction != null)
  734. {
  735. onCaughtExceptionFinallyProcessAction(performanceCounter);
  736. }
  737. }
  738. }
  739. }
  740. }
  741. if (onCounterChangedProcessAction != null)
  742. {
  743. var caughtException = false;
  744. try
  745. {
  746. onCounterChangedProcessAction(performanceCounter);
  747. }
  748. catch (Exception e)
  749. {
  750. caughtException = true;
  751. var reThrow = true;
  752. if (onCaughtExceptionProcessFunc != null)
  753. {
  754. reThrow = onCaughtExceptionProcessFunc(performanceCounter, e);
  755. }
  756. if (reThrow)
  757. {
  758. throw new Exception("ReThrow Exception On Caught Excepion", e);
  759. }
  760. }
  761. finally
  762. {
  763. if (caughtException)
  764. {
  765. if (onCaughtExceptionFinallyProcessAction != null)
  766. {
  767. onCaughtExceptionFinallyProcessAction(performanceCounter);
  768. }
  769. }
  770. }
  771. }
  772. return r;
  773. }
  774. public static void ChangeAverageTimerCounterValueWithTryCatchExceptionFinally
  775. (
  776. this PerformanceCounter performanceCounter
  777. , bool enabled
  778. , PerformanceCounter basePerformanceCounter
  779. , Action onCountPerformanceInnerProcessAction //= null
  780. , Func<PerformanceCounter, Exception, bool> onCaughtExceptionProcessFunc //= null
  781. , Action<PerformanceCounter, PerformanceCounter> onCaughtExceptionFinallyProcessAction //= null
  782. )
  783. {
  784. if (enabled)
  785. {
  786. var stopwatch = Stopwatch.StartNew();
  787. if (onCountPerformanceInnerProcessAction != null)
  788. {
  789. var caughtException = false;
  790. try
  791. {
  792. onCountPerformanceInnerProcessAction();
  793. }
  794. catch (Exception e)
  795. {
  796. caughtException = true;
  797. var reThrow = true;
  798. if (onCaughtExceptionProcessFunc != null)
  799. {
  800. reThrow = onCaughtExceptionProcessFunc(performanceCounter, e);
  801. }
  802. if (reThrow)
  803. {
  804. throw new Exception("ReThrow Exception On Caught Excepion", e);
  805. }
  806. }
  807. finally
  808. {
  809. stopwatch.Stop();
  810. performanceCounter.IncrementBy(stopwatch.ElapsedTicks);
  811. stopwatch = null;
  812. basePerformanceCounter.Increment();
  813. if (caughtException)
  814. {
  815. if (onCaughtExceptionFinallyProcessAction != null)
  816. {
  817. onCaughtExceptionFinallyProcessAction(performanceCounter, basePerformanceCounter);
  818. }
  819. }
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. namespace Microshaoft
  827. {
  828. using System;
  829. using System.Diagnostics;
  830. [FlagsAttribute]
  831. public enum MultiPerformanceCountersTypeFlags : ushort
  832. {
  833. None = 0,
  834. ProcessCounter = 1,
  835. ProcessingCounter = 2,
  836. ProcessedCounter = 4,
  837. ProcessedAverageTimerCounter = 8,
  838. ProcessedRateOfCountsPerSecondCounter = 16
  839. };
  840. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
  841. public class PerformanceCounterDefinitionAttribute : Attribute
  842. {
  843. public PerformanceCounterType CounterType;
  844. public string CounterName;
  845. }
  846. }
  847. namespace Microshaoft
  848. {
  849. using System.Diagnostics;
  850. using System.Linq;
  851. public static class PerformanceCountersHelper
  852. {
  853. public static void AttachPerformanceCountersToProperties<T>
  854. (
  855. string performanceCounterInstanceName
  856. , string category
  857. , T target //= default(T)
  858. )
  859. {
  860. var type = typeof(T);
  861. var propertiesList = type.GetProperties().ToList();
  862. propertiesList = propertiesList.Where
  863. (
  864. (pi) =>
  865. {
  866. var parameters = pi.GetIndexParameters();
  867. return
  868. (
  869. pi.PropertyType == typeof(PerformanceCounter)
  870. && (parameters == null ? 0 : parameters.Length) <= 0
  871. );
  872. }
  873. ).ToList();
  874. if (PerformanceCounterCategory.Exists(category))
  875. {
  876. propertiesList.ForEach
  877. (
  878. (pi) =>
  879. {
  880. if (PerformanceCounterCategory.CounterExists(pi.Name, category))
  881. {
  882. if (PerformanceCounterCategory.InstanceExists(performanceCounterInstanceName, category))
  883. {
  884. //var pc = new PerformanceCounter(category, pi.Name, instanceName, false);
  885. //pc.InstanceName = instanceName;
  886. //pc.RemoveInstance();
  887. }
  888. }
  889. }
  890. );
  891. //PerformanceCounterCategory.Delete(category);
  892. }
  893. if (!PerformanceCounterCategory.Exists(category))
  894. {
  895. var ccdc = new CounterCreationDataCollection();
  896. propertiesList.ForEach
  897. (
  898. (pi) =>
  899. {
  900. var propertyName = pi.Name;
  901. var performanceCounterType = PerformanceCounterType.NumberOfItems64;
  902. var performanceCounterName = propertyName;
  903. var attribute = pi.GetCustomAttributes(false).FirstOrDefault
  904. (
  905. (x) =>
  906. {
  907. return x as PerformanceCounterDefinitionAttribute != null;
  908. }
  909. ) as PerformanceCounterDefinitionAttribute;
  910. if (attribute != null)
  911. {
  912. var counterName = attribute.CounterName;
  913. if (!string.IsNullOrEmpty(counterName))
  914. {
  915. performanceCounterName = counterName;
  916. }
  917. var counterType = attribute.CounterType;
  918. //if (counterType != null)
  919. {
  920. performanceCounterType = counterType;
  921. }
  922. }
  923. var ccd = PerformanceCountersHelper.GetCounterCreationData
  924. (
  925. performanceCounterName
  926. , performanceCounterType
  927. );
  928. ccdc.Add(ccd);
  929. }
  930. );
  931. PerformanceCounterCategory.Create
  932. (
  933. category,
  934. string.Format("{0} Category Help.", category),
  935. PerformanceCounterCategoryType.MultiInstance,
  936. ccdc
  937. );
  938. }
  939. propertiesList.ForEach
  940. (
  941. (pi) =>
  942. {
  943. var propertyName = pi.Name;
  944. var performanceCounterType = PerformanceCounterType.NumberOfItems64;
  945. var performanceCounterName = propertyName;
  946. var attribute = pi.GetCustomAttributes(false).FirstOrDefault
  947. (
  948. (x) =>
  949. {
  950. return x as PerformanceCounterDefinitionAttribute != null;
  951. }
  952. ) as PerformanceCounterDefinitionAttribute;
  953. if (attribute != null)
  954. {
  955. var counterName = attribute.CounterName;
  956. if (!string.IsNullOrEmpty(counterName))
  957. {
  958. performanceCounterName = counterName;
  959. }
  960. var counterType = attribute.CounterType;
  961. //if (counterType != null)
  962. {
  963. performanceCounterType = counterType;
  964. }
  965. }
  966. var pc = new PerformanceCounter()
  967. {
  968. CategoryName = category
  969. ,
  970. CounterName = performanceCounterName
  971. ,
  972. InstanceLifetime = PerformanceCounterInstanceLifetime.Process
  973. ,
  974. InstanceName = performanceCounterInstanceName
  975. ,
  976. ReadOnly = false
  977. ,
  978. RawValue = 0
  979. };
  980. if (pi.GetGetMethod().IsStatic)
  981. {
  982. var setter = DynamicPropertyAccessor.CreateSetStaticPropertyValueAction<PerformanceCounter>(type, propertyName);
  983. setter(pc);
  984. }
  985. else
  986. {
  987. if (target != null)
  988. {
  989. var setter = DynamicPropertyAccessor.CreateSetPropertyValueAction<PerformanceCounter>(type, propertyName);
  990. setter(target, pc);
  991. }
  992. }
  993. }
  994. );
  995. }
  996. public static CounterCreationData GetCounterCreationData(string counterName, PerformanceCounterType performanceCounterType)
  997. {
  998. return new CounterCreationData()
  999. {
  1000. CounterName = counterName
  1001. ,
  1002. CounterHelp = string.Format("{0} Help", counterName)
  1003. ,
  1004. CounterType = performanceCounterType
  1005. };
  1006. }
  1007. }
  1008. }
  1009. namespace Microshaoft
  1010. {
  1011. using System;
  1012. using System.Threading;
  1013. public static class ReaderWriterLockSlimHelper
  1014. {
  1015. public static bool TryEnterWriterLockSlimWrite<T>
  1016. (
  1017. ref T target
  1018. , T newValue
  1019. , int enterTimeOutSeconds
  1020. )
  1021. where T : class
  1022. {
  1023. bool r = false;
  1024. var rwls = new ReaderWriterLockSlim();
  1025. int timeOut = Timeout.Infinite;
  1026. if (enterTimeOutSeconds >= 0)
  1027. {
  1028. timeOut = enterTimeOutSeconds * 1000;
  1029. }
  1030. try
  1031. {
  1032. r = (rwls.TryEnterWriteLock(timeOut));
  1033. if (r)
  1034. {
  1035. Interlocked.Exchange<T>(ref target, newValue);
  1036. r = true;
  1037. }
  1038. }
  1039. finally
  1040. {
  1041. if (r)
  1042. {
  1043. rwls.ExitWriteLock();
  1044. }
  1045. }
  1046. return r;
  1047. }
  1048. public static bool TryEnterWriterLockSlim
  1049. (
  1050. Action action
  1051. , int enterTimeOutSeconds
  1052. )
  1053. {
  1054. bool r = false;
  1055. if (action != null)
  1056. {
  1057. var rwls = new ReaderWriterLockSlim();
  1058. int timeOut = Timeout.Infinite;
  1059. if (enterTimeOutSeconds >= 0)
  1060. {
  1061. timeOut = enterTimeOutSeconds * 1000;
  1062. }
  1063. try
  1064. {
  1065. r = (rwls.TryEnterWriteLock(timeOut));
  1066. if (r)
  1067. {
  1068. action();
  1069. r = true;
  1070. }
  1071. }
  1072. finally
  1073. {
  1074. if (r)
  1075. {
  1076. rwls.ExitWriteLock();
  1077. }
  1078. }
  1079. }
  1080. return r;
  1081. }
  1082. }
  1083. }
  1084. namespace Microshaoft
  1085. {
  1086. using System;
  1087. using System.Linq;
  1088. using System.Linq.Expressions;
  1089. using System.Reflection;
  1090. public class DynamicPropertyAccessor
  1091. {
  1092. private static Assembly GetAssemblyByTypeName(string typeName)
  1093. {
  1094. return
  1095. AppDomain
  1096. .CurrentDomain
  1097. .GetAssemblies()
  1098. .First
  1099. (
  1100. (a) =>
  1101. {
  1102. return
  1103. a
  1104. .GetTypes()
  1105. .Any
  1106. (
  1107. (t) =>
  1108. {
  1109. return
  1110. (
  1111. t.FullName
  1112. == typeName
  1113. );
  1114. }
  1115. );
  1116. }
  1117. );
  1118. }
  1119. public static Func<object, object> CreateGetPropertyValueFunc
  1120. (
  1121. string typeName
  1122. , string propertyName
  1123. , bool isTypeFromAssembly = false
  1124. )
  1125. {
  1126. Type type;
  1127. if (isTypeFromAssembly)
  1128. {
  1129. var assembly = GetAssemblyByTypeName(typeName);
  1130. type = assembly.GetType(typeName);
  1131. }
  1132. else
  1133. {
  1134. type = Type.GetType(typeName);
  1135. }
  1136. return CreateGetPropertyValueFunc(type, propertyName);
  1137. }
  1138. public static Func<object, object> CreateGetPropertyValueFunc
  1139. (
  1140. Type type
  1141. , string propertyName
  1142. )
  1143. {
  1144. var target = Expression.Parameter(typeof(object));
  1145. var castTarget = Expression.Convert(target, type);
  1146. var getPropertyValue = Expression.Property(castTarget, propertyName);
  1147. var castPropertyValue = Expression.Convert(getPropertyValue, typeof(object));
  1148. var lambda = Expression.Lambda<Func<object, object>>(castPropertyValue, target);
  1149. return lambda.Compile();
  1150. }
  1151. public static Func<object, TProperty> CreateGetPropertyValueFunc<TProperty>
  1152. (
  1153. string typeName
  1154. , string propertyName
  1155. , bool isTypeFromAssembly = false
  1156. )
  1157. {
  1158. Type type;
  1159. if (isTypeFromAssembly)
  1160. {
  1161. var assembly = GetAssemblyByTypeName(typeName);
  1162. type = assembly.GetType(typeName);
  1163. }
  1164. else
  1165. {
  1166. type = Type.GetType(typeName);
  1167. }
  1168. return CreateGetPropertyValueFunc<TProperty>(type, propertyName);
  1169. }
  1170. public static Func<object, TProperty> CreateGetPropertyValueFunc<TProperty>
  1171. (
  1172. Type type
  1173. , string propertyName
  1174. )
  1175. {
  1176. var target = Expression.Parameter(typeof(object));
  1177. var castTarget = Expression.Convert(target, type);
  1178. var getPropertyValue = Expression.Property(castTarget, propertyName);
  1179. var lambda = Expression.Lambda<Func<object, TProperty>>(getPropertyValue, target);
  1180. return lambda.Compile();
  1181. }
  1182. public static Func<TProperty> CreateGetStaticPropertyValueFunc<TProperty>
  1183. (
  1184. string typeName
  1185. , string propertyName
  1186. , bool isTypeFromAssembly = false
  1187. )
  1188. {
  1189. Type type;
  1190. if (isTypeFromAssembly)
  1191. {
  1192. var assembly = GetAssemblyByTypeName(typeName);
  1193. type = assembly.GetType(typeName);
  1194. }
  1195. else
  1196. {
  1197. type = Type.GetType(typeName);
  1198. }
  1199. return CreateGetStaticPropertyValueFunc<TProperty>(type, propertyName);
  1200. }
  1201. public static Func<TProperty> CreateGetStaticPropertyValueFunc<TProperty>
  1202. (
  1203. Type type
  1204. , string propertyName
  1205. )
  1206. {
  1207. Func<TProperty> func = null;
  1208. var property = type.GetProperty(propertyName, typeof(TProperty));
  1209. if (property == null)
  1210. {
  1211. property =
  1212. type
  1213. .GetProperties()
  1214. .ToList()
  1215. .FirstOrDefault
  1216. (
  1217. (x) =>
  1218. {
  1219. return
  1220. (
  1221. x.Name.ToLower()
  1222. == propertyName.ToLower()
  1223. );
  1224. }
  1225. );
  1226. }
  1227. if (property != null)
  1228. {
  1229. var getPropertyValue = Expression.Property(null, property);
  1230. var lambda = Expression.Lambda<Func<TProperty>>(getPropertyValue, null);
  1231. func = lambda.Compile();
  1232. }
  1233. return func;
  1234. }
  1235. public static Func<object> CreateGetStaticPropertyValueFunc
  1236. (
  1237. Type type
  1238. , string propertyName
  1239. )
  1240. {
  1241. Func<object> func = null;
  1242. var property = type.GetProperty(propertyName);
  1243. if (property == null)
  1244. {
  1245. property =
  1246. type
  1247. .GetProperties()
  1248. .ToList()
  1249. .FirstOrDefault
  1250. (
  1251. (x) =>
  1252. {
  1253. return
  1254. (
  1255. x.Name.ToLower()
  1256. == propertyName.ToLower()
  1257. );
  1258. }
  1259. );
  1260. }
  1261. if (property != null)
  1262. {
  1263. var getPropertyValue = Expression.Property(null, property);
  1264. var castPropertyValue = Expression.Convert(getPropertyValue, typeof(object));
  1265. var lambda = Expression.Lambda<Func<object>>(castPropertyValue, null);
  1266. func = lambda.Compile();
  1267. }
  1268. return func;
  1269. }
  1270. public static Func<object> CreateGetStaticPropertyValueFunc
  1271. (
  1272. string typeName
  1273. , string propertyName
  1274. , bool isTypeFromAssembly = false
  1275. )
  1276. {
  1277. Type type;
  1278. if (isTypeFromAssembly)
  1279. {
  1280. var assembly = GetAssemblyByTypeName(typeName);
  1281. type = assembly.GetType(typeName);
  1282. }
  1283. else
  1284. {
  1285. type = Type.GetType(typeName);
  1286. }
  1287. return CreateGetStaticPropertyValueFunc(type, propertyName);
  1288. }
  1289. public static Action<object, object> CreateSetPropertyValueAction
  1290. (
  1291. Type type
  1292. , string propertyName
  1293. )
  1294. {
  1295. Action<object, object> action = null;
  1296. var property = type.GetProperty(propertyName);
  1297. if (property == null)
  1298. {
  1299. property =
  1300. type
  1301. .GetProperties()
  1302. .ToList()
  1303. .FirstOrDefault
  1304. (
  1305. (x) =>
  1306. {
  1307. return
  1308. (
  1309. x.Name.ToLower()
  1310. == propertyName.ToLower()
  1311. );
  1312. }
  1313. );
  1314. }
  1315. if (property != null)
  1316. {
  1317. var target = Expression.Parameter(typeof(object));
  1318. var propertyValue = Expression.Parameter(typeof(object));
  1319. var castTarget = Expression.Convert(target, type);
  1320. var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
  1321. var getSetMethod = property.GetSetMethod();
  1322. if (getSetMethod == null)
  1323. {
  1324. getSetMethod = property.GetSetMethod(true);
  1325. }
  1326. var call = Expression.Call(castTarget, getSetMethod, castPropertyValue);
  1327. var lambda = Expression.Lambda<Action<object, object>>(call, target, propertyValue);
  1328. action = lambda.Compile();
  1329. }
  1330. return action;
  1331. }
  1332. public static Action<object, object> CreateSetPropertyValueAction
  1333. (
  1334. string typeName
  1335. , string propertyName
  1336. , bool isTypeFromAssembly = false
  1337. )
  1338. {
  1339. Type type;
  1340. if (isTypeFromAssembly)
  1341. {
  1342. var assembly = GetAssemblyByTypeName(typeName);
  1343. type = assembly.GetType(typeName);
  1344. }
  1345. else
  1346. {
  1347. type = Type.GetType(typeName);
  1348. }
  1349. return CreateSetPropertyValueAction(type, propertyName);
  1350. }
  1351. public static Action<object, TProperty> CreateSetPropertyValueAction<TProperty>
  1352. (
  1353. Type type
  1354. , string propertyName
  1355. )
  1356. {
  1357. Action<object, TProperty> action = null;
  1358. var property = type.GetProperty(propertyName);
  1359. if (property == null)
  1360. {
  1361. property =
  1362. type
  1363. .GetProperties()
  1364. .ToList()
  1365. .FirstOrDefault
  1366. (
  1367. (x) =>
  1368. {
  1369. return
  1370. (
  1371. x.Name.ToLower()
  1372. == propertyName.ToLower()
  1373. );
  1374. }
  1375. );
  1376. }
  1377. if (property != null)
  1378. {
  1379. var target = Expression.Parameter(typeof(object));
  1380. var propertyValue = Expression.Parameter(typeof(TProperty));
  1381. var castTarget = Expression.Convert(target, type);
  1382. var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
  1383. var getSetMethod = property.GetSetMethod();
  1384. if (getSetMethod == null)
  1385. {
  1386. getSetMethod = property.GetSetMethod(true);
  1387. }
  1388. var call = Expression.Call(castTarget, getSetMethod, castPropertyValue);
  1389. var lambda = Expression.Lambda<Action<object, TProperty>>(call, target, propertyValue);
  1390. action = lambda.Compile();
  1391. }
  1392. return action;
  1393. }
  1394. public static Action<object, TProperty> CreateSetPropertyValueAction<TProperty>
  1395. (
  1396. string typeName
  1397. , string propertyName
  1398. , bool isTypeFromAssembly = false
  1399. )
  1400. {
  1401. Type type;
  1402. if (isTypeFromAssembly)
  1403. {
  1404. var assembly = GetAssemblyByTypeName(typeName);
  1405. type = assembly.GetType(typeName);
  1406. }
  1407. else
  1408. {
  1409. type = Type.GetType(typeName);
  1410. }
  1411. return CreateSetPropertyValueAction<TProperty>(type, propertyName);
  1412. }
  1413. public static Action<object> CreateSetStaticPropertyValueAction
  1414. (
  1415. Type type
  1416. , string propertyName
  1417. )
  1418. {
  1419. Action<object> action = null;
  1420. var property = type.GetProperty(propertyName);
  1421. if (property == null)
  1422. {
  1423. property =
  1424. type
  1425. .GetProperties()
  1426. .ToList()
  1427. .FirstOrDefault
  1428. (
  1429. (x) =>
  1430. {
  1431. return
  1432. (
  1433. x.Name.ToLower()
  1434. == propertyName.ToLower()
  1435. );
  1436. }
  1437. );
  1438. }
  1439. if (property != null)
  1440. {
  1441. var propertyValue = Expression.Parameter(typeof(object));
  1442. var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
  1443. var getSetMethod = property.GetSetMethod();
  1444. if (getSetMethod == null)
  1445. {
  1446. getSetMethod = property.GetSetMethod(true);
  1447. }
  1448. var call = Expression.Call(null, getSetMethod, castPropertyValue);
  1449. var lambda = Expression.Lambda<Action<object>>(call, propertyValue);
  1450. action = lambda.Compile();
  1451. }
  1452. return action;
  1453. }
  1454. public static Action<object> CreateSetStaticPropertyValueAction
  1455. (
  1456. string typeName
  1457. , string propertyName
  1458. , bool isTypeFromAssembly = false
  1459. )
  1460. {
  1461. Type type;
  1462. if (isTypeFromAssembly)
  1463. {
  1464. var assembly = GetAssemblyByTypeName(typeName);
  1465. type = assembly.GetType(typeName);
  1466. }
  1467. else
  1468. {
  1469. type = Type.GetType(typeName);
  1470. }
  1471. return CreateSetStaticPropertyValueAction(type, propertyName);
  1472. }
  1473. public static Action<TProperty> CreateSetStaticPropertyValueAction<TProperty>
  1474. (
  1475. Type type
  1476. , string propertyName
  1477. )
  1478. {
  1479. Action<TProperty> action = null;
  1480. var property = type.GetProperty(propertyName);
  1481. if (property == null)
  1482. {
  1483. property =
  1484. type
  1485. .GetProperties()
  1486. .ToList()
  1487. .FirstOrDefault
  1488. (
  1489. (x) =>
  1490. {
  1491. return
  1492. (
  1493. x.Name.ToLower()
  1494. == propertyName.ToLower()
  1495. );
  1496. }
  1497. );
  1498. }
  1499. if (property != null)
  1500. {
  1501. var propertyValue = Expression.Parameter(typeof(TProperty));
  1502. //var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
  1503. var getSetMethod = property.GetSetMethod();
  1504. if (getSetMethod == null)
  1505. {
  1506. getSetMethod = property.GetSetMethod(true);
  1507. }
  1508. var call = Expression.Call(null, getSetMethod, propertyValue);
  1509. var lambda = Expression.Lambda<Action<TProperty>>(call, propertyValue);
  1510. action = lambda.Compile();
  1511. }
  1512. return action;
  1513. }
  1514. public static Action<TProperty> CreateSetStaticPropertyValueAction<TProperty>
  1515. (
  1516. string typeName
  1517. , string propertyName
  1518. , bool isTypeFromAssembly = false
  1519. )
  1520. {
  1521. Type type;
  1522. if (isTypeFromAssembly)
  1523. {
  1524. var assembly = GetAssemblyByTypeName(typeName);
  1525. type = assembly.GetType(typeName);
  1526. }
  1527. else
  1528. {
  1529. type = Type.GetType(typeName);
  1530. }
  1531. return CreateSetStaticPropertyValueAction<TProperty>(type, propertyName);
  1532. }
  1533. }
  1534. }
  1535. //以下 only for .NET 3.5 =============================
  1536. #if NET35
  1537. namespace System.Threading.Tasks
  1538. {
  1539. using System;
  1540. using System.Threading;
  1541. public class ParallelOptions
  1542. {
  1543. public int MaxDegreeOfParallelism
  1544. {
  1545. set;
  1546. get;
  1547. }
  1548. }
  1549. public static class Parallel
  1550. {
  1551. public static void For
  1552. (
  1553. int from
  1554. , int to
  1555. , ParallelOptions options
  1556. , Action<int> action
  1557. )
  1558. {
  1559. var iterations = to - from;
  1560. var threads = options.MaxDegreeOfParallelism;
  1561. var ares = new AutoResetEvent[threads];
  1562. var i = 0;
  1563. var count = 0;
  1564. Array.ForEach
  1565. (
  1566. ares
  1567. , (x) =>
  1568. {
  1569. var are = new AutoResetEvent(false);
  1570. ares[i++] = are;
  1571. new Thread
  1572. (
  1573. new ThreadStart
  1574. (
  1575. () =>
  1576. {
  1577. while (true)
  1578. {
  1579. int j = Interlocked.Increment(ref from);
  1580. if (j <= to)
  1581. {
  1582. Interlocked.Increment(ref count);
  1583. action(j);
  1584. }
  1585. else
  1586. {
  1587. break;
  1588. }
  1589. }
  1590. are.Set();
  1591. }
  1592. )
  1593. ).Start();
  1594. }
  1595. );
  1596. WaitHandle.WaitAll(ares);
  1597. Console.WriteLine(count);
  1598. }
  1599. }
  1600. }
  1601. #endif

CodeTimerPerformance EasyPerformanceCounterHelper .NET 4.5的更多相关文章

随机推荐

  1. windows下pip安装python模块时报错总结

    http://www.cnblogs.com/liaojiafa/p/5100550.html 前言: 这几天把python版本升级后,发现pip安装模块好多都报错(暂不确定是不是因为升级导致的),我 ...

  2. SDL鼠标事件

    鼠标事件有这么多种,手柄的可以忽视,Sdl.SDL_KEYDOWN,Sdl.SDL_KEYUP,Sdl.SDL_MOUSEMOTION,Sdl.SDL_MOUSEBUTTONDOWN,Sdl.SDL_ ...

  3. [Unity3D]脚本生命周期学习

    脚本的生命周期 继承于MonoBehaviour的类对象无需手动实例化,由引擎来决定实例化的时机 Awake:每当脚本被加载的时候调用一次,就是说即使脚本没有被勾选,也会调用一次,主要用来做一些初始化 ...

  4. C#直接赋值和反射赋值(无GC)的性能比较

    using System; using System.Reflection; using System.Diagnostics; using System.Runtime.InteropService ...

  5. ecshop后台 计划任务

    计划任务定时清理掉设置后的内容 主要针对单表删除(日志,):对于多表删除,不太好用(订单+订单商品+订单日志) 结构: 1.计划任务语言包:languages\zh_cn\cron\ 2.php文件: ...

  6. CSS选择器优先级总结

    CSS三大特性-- 继承. 优先级和层叠. 继承:即子类元素继承父类的样式; 优先级:是指不同类别样式的权重比较; 层叠:是说当数量相同时,通过层叠(后者覆盖前者)的样式. css选择符分类 首先来看 ...

  7. 2013成都网络赛 J A Bit Fun(水题)

    A Bit Fun Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  8. 安卓TabHost页面

    <?xml version="1.0" encoding="UTF-8"?> <!-- TabHost组件id值不可变--> <T ...

  9. php万年历

    最近学习php循环.日期显示.GET方式请求,进而实现了一个小程序. 直接上代码: <?php header("Content-type:text/html; charset=UTF- ...

  10. 字符串匹配:KMP算法

    一.原理: KMP算法是由Knuth,Morris,Pratt共同提出的模式匹配算法,其对于任何模式和目标序列,都可以在线性时间内完成匹配查找,而不会发生退化,是一个非常优秀的模式匹配算法.朴素算法( ...