標籤:
學習書籍: <C#本質論>
1--C#5.0之後推薦使用TPL(Task Parallel Libray 工作平行程式庫) 和PLINQ(Parallel LINQ, 並行Linq).
其次是TAP(Task-based Asynchronous Pattern, 基於任務的非同步模式).
--用AggregateException處理Task上的未處理異常.
--取消任務. CancellationToken
--async修飾方法, 返回Task. task.wait(100)可以阻塞現場. async方法內await 啟線程執行.
==> 第一部分, 5.0推薦的線程使用方式.
2--學習了Task 等線程同步使用方式:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace Task1{ class Program { const int _Total = 99999; static long _Count = 0; readonly static object _Sync = new Object(); static void Main(string[] args) { //Task task = Task.Run(()=>Decrement()); //for (int i = 0; i < _Total; i++) //{ // _Count++; //} //task.Wait(); //Console.WriteLine("Count = {0}", _Count); //CountAsync(); //int x = 0; //Parallel.For(0, 999999, i => // { // x++; // x--; // }); //Console.WriteLine("Count = {0}",x); Task task = Task.Run(() => Decrement()); for (int i = 0; i < _Total; i++) { bool lockTaken = false; try { Monitor.Enter(_Sync, ref lockTaken); _Count++; } finally { if (lockTaken) { Monitor.Enter(_Sync); } } } task.Wait(); Console.WriteLine("Count = {0}", _Count); Console.ReadKey(); } public static async void CountAsync() { Task task = Task.Run(() => Decrement()); for (int i = 0; i < _Total; i++) { _Count++; } await task; Console.WriteLine("Count = {0}", _Count); } static void Decrement() { for (int i = 0; i < _Total; i++) { bool lockTaken = false; try { Monitor.Enter(_Sync, ref lockTaken); _Count--; } finally { if (lockTaken) { Monitor.Exit(_Sync); } } } } }}
==> 第二部分.
TPL和C#5.0之前的多線程模式
1. 調用APM #region String url = "www.baidu.com"; if (args.Length > 0) { url = args[0]; } Console.WriteLine(url); WebRequest webRequest = WebRequest.Create(url); IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); while(!asyncResult.AsyncWaitHandle.WaitOne(100)) { Console.Write("."); } WebResponse response = webRequest.EndGetResponse(asyncResult); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { int length = reader.ReadToEnd().Length; Console.WriteLine(length); }
2-- 複雜帶狀態的操作
1--CPS 連續調用樣式. 的fire-and-forget模式. 減少了直接再beginXXX方法後調用EndXXX方法.
通過CPS,"登記"非同步方法呼叫結束時執行的代碼.
3-- 在APM方法間傳遞狀態
1--可以通過Lambda完成委託BeginXXX調用.
C#5.0之後推薦使用TPL(Task Parallel Libray 工作平行程式庫) 和PLINQ(Parallel LINQ, 並行Linq). 其次是TAP(Task-based Asynchronous Pattern, 基於任務的非同步模式)