{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/csharp-multithreading/",
  "atlas": "https://www.pystone.net/?node=csharp-multithreading#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/csharp-multithreading.md",
  "context": "https://www.pystone.net/notes/csharp-multithreading.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:csharp-multithreading",
  "slug": "csharp-multithreading",
  "title": "C#多线程",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "C 多线程",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "aaa82a164ee5d19fe6ddae7e4704d2c01fcf907601d348ea7a15302d91187644",
  "assets": [
    {
      "reference": "assets/1607587474930.png",
      "url": "/media/9cbeb18d0d6aedd5c9bb.png",
      "mediaType": "image/png",
      "contentHash": "9cbeb18d0d6aedd5c9bbbd9f0f1d9507f3e2e8b9a23c1d979dcb84e42b7d6d91",
      "byteLength": 230172,
      "width": 768,
      "height": 397
    },
    {
      "reference": "assets/1607591150344.png",
      "url": "/media/d4652d2c3fd2c7dd7d4d.png",
      "mediaType": "image/png",
      "contentHash": "d4652d2c3fd2c7dd7d4da25b9e5a432b07cedb7d6e1f1a137f5b557a58a574ad",
      "byteLength": 29792,
      "width": 643,
      "height": 254
    },
    {
      "reference": "assets/1607590249171.png",
      "url": "/media/4ef3565c668249ac60ca.png",
      "mediaType": "image/png",
      "contentHash": "4ef3565c668249ac60ca3a5b84d2d7ed1b2b55bc710b53ac82253353fa6ef2c5",
      "byteLength": 67084,
      "width": 642,
      "height": 436
    },
    {
      "reference": "assets/1607597574530.png",
      "url": "/media/9261be729f09d11cc0cd.png",
      "mediaType": "image/png",
      "contentHash": "9261be729f09d11cc0cdc8f472901fee07719fd829b8c5a57f6f285b087141f4",
      "byteLength": 62507,
      "width": 533,
      "height": 717
    },
    {
      "reference": "assets/1607602967865.png",
      "url": "/media/1a1e454359b932188c56.png",
      "mediaType": "image/png",
      "contentHash": "1a1e454359b932188c56cb33644c438319a2cd6d24cc899c5a6cb633979d2bee",
      "byteLength": 43103,
      "width": 1044,
      "height": 631
    },
    {
      "reference": "assets/1607587813963.png",
      "url": "/media/ab5fba0987e913f26884.png",
      "mediaType": "image/png",
      "contentHash": "ab5fba0987e913f268849a29be375477191ac60d34d7efcdec084e98a0528d3d",
      "byteLength": 151007,
      "width": 1920,
      "height": 993
    },
    {
      "reference": "assets/1607670556723.png",
      "url": "/media/ef20152c4a4ff065b5d0.png",
      "mediaType": "image/png",
      "contentHash": "ef20152c4a4ff065b5d0ee8acf9beaf1b0b316313f013c44e5e04c7b8f98d812",
      "byteLength": 24606,
      "width": 345,
      "height": 696
    },
    {
      "reference": "assets/1607671750908.png",
      "url": "/media/80793f1dc1baa0df9fda.png",
      "mediaType": "image/png",
      "contentHash": "80793f1dc1baa0df9fdad5e35d5cc29d516b1350424f30edd47090072105ea40",
      "byteLength": 21481,
      "width": 827,
      "height": 389
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "C#多线程",
      "anchor": "c多线程",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#c%E5%A4%9A%E7%BA%BF%E7%A8%8B"
    },
    {
      "depth": 2,
      "text": "concepts",
      "anchor": "concepts",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#concepts"
    },
    {
      "depth": 3,
      "text": "Multitasking",
      "anchor": "multitasking",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#multitasking"
    },
    {
      "depth": 4,
      "text": "process",
      "anchor": "process",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#process"
    },
    {
      "depth": 4,
      "text": "Thread",
      "anchor": "thread",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#thread"
    },
    {
      "depth": 2,
      "text": "Multithreading in C Sharp",
      "anchor": "multithreading-in-c-sharp",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#multithreading-in-c-sharp"
    },
    {
      "depth": 3,
      "text": "Thread",
      "anchor": "thread-1",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#thread-1"
    },
    {
      "depth": 4,
      "text": "状态",
      "anchor": "状态",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%8A%B6%E6%80%81"
    },
    {
      "depth": 4,
      "text": "启动与参数传递",
      "anchor": "启动与参数传递",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%90%AF%E5%8A%A8%E4%B8%8E%E5%8F%82%E6%95%B0%E4%BC%A0%E9%80%92"
    },
    {
      "depth": 5,
      "text": "委托传参(需要装箱拆箱)",
      "anchor": "委托传参需要装箱拆箱",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%A7%94%E6%89%98%E4%BC%A0%E5%8F%82%E9%9C%80%E8%A6%81%E8%A3%85%E7%AE%B1%E6%8B%86%E7%AE%B1"
    },
    {
      "depth": 5,
      "text": "使用静态变量或类成员变量",
      "anchor": "使用静态变量或类成员变量",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E4%BD%BF%E7%94%A8%E9%9D%99%E6%80%81%E5%8F%98%E9%87%8F%E6%88%96%E7%B1%BB%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F"
    },
    {
      "depth": 5,
      "text": "委托 + 两层函数避免Boxing",
      "anchor": "委托-两层函数避免boxing",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%A7%94%E6%89%98-%E4%B8%A4%E5%B1%82%E5%87%BD%E6%95%B0%E9%81%BF%E5%85%8Dboxing"
    },
    {
      "depth": 4,
      "text": "阻塞（Block）",
      "anchor": "阻塞block",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E9%98%BB%E5%A1%9Eblock"
    },
    {
      "depth": 4,
      "text": "线程优先级、前台线程和后台线程",
      "anchor": "线程优先级前台线程和后台线程",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%BA%BF%E7%A8%8B%E4%BC%98%E5%85%88%E7%BA%A7%E5%89%8D%E5%8F%B0%E7%BA%BF%E7%A8%8B%E5%92%8C%E5%90%8E%E5%8F%B0%E7%BA%BF%E7%A8%8B"
    },
    {
      "depth": 3,
      "text": "多线程竞争",
      "anchor": "多线程竞争",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%AB%9E%E4%BA%89"
    },
    {
      "depth": 4,
      "text": "lock & Monitor 与线程锁",
      "anchor": "lock-monitor-与线程锁",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#lock-monitor-%E4%B8%8E%E7%BA%BF%E7%A8%8B%E9%94%81"
    },
    {
      "depth": 4,
      "text": "原子操作",
      "anchor": "原子操作",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C"
    },
    {
      "depth": 4,
      "text": "Mutex类与进程同步",
      "anchor": "mutex类与进程同步",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#mutex%E7%B1%BB%E4%B8%8E%E8%BF%9B%E7%A8%8B%E5%90%8C%E6%AD%A5"
    },
    {
      "depth": 4,
      "text": "Semaphore（信号量）与资源池",
      "anchor": "semaphore信号量与资源池",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#semaphore%E4%BF%A1%E5%8F%B7%E9%87%8F%E4%B8%8E%E8%B5%84%E6%BA%90%E6%B1%A0"
    },
    {
      "depth": 4,
      "text": "ReaderWriterLockSlim",
      "anchor": "readerwriterlockslim",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#readerwriterlockslim"
    },
    {
      "depth": 3,
      "text": "线程间通信与同步",
      "anchor": "线程间通信与同步",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1%E4%B8%8E%E5%90%8C%E6%AD%A5"
    },
    {
      "depth": 4,
      "text": "AutoRestEvent, ManualResetEvent",
      "anchor": "autorestevent-manualresetevent",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#autorestevent-manualresetevent"
    },
    {
      "depth": 4,
      "text": "CountdownEvent 与 线程完成数",
      "anchor": "countdownevent-与-线程完成数",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#countdownevent-%E4%B8%8E-%E7%BA%BF%E7%A8%8B%E5%AE%8C%E6%88%90%E6%95%B0"
    },
    {
      "depth": 4,
      "text": "Barrier 类",
      "anchor": "barrier-类",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#barrier-%E7%B1%BB"
    },
    {
      "depth": 4,
      "text": "线程等待进阶",
      "anchor": "线程等待进阶",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%BA%BF%E7%A8%8B%E7%AD%89%E5%BE%85%E8%BF%9B%E9%98%B6"
    },
    {
      "depth": 3,
      "text": "ThreadPool 线程池",
      "anchor": "threadpool-线程池",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#threadpool-%E7%BA%BF%E7%A8%8B%E6%B1%A0"
    },
    {
      "depth": 4,
      "text": "ThreadPool 类",
      "anchor": "threadpool-类",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#threadpool-%E7%B1%BB"
    },
    {
      "depth": 4,
      "text": "适用性",
      "anchor": "适用性",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E9%80%82%E7%94%A8%E6%80%A7"
    },
    {
      "depth": 4,
      "text": "具体用法",
      "anchor": "具体用法",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%85%B7%E4%BD%93%E7%94%A8%E6%B3%95"
    },
    {
      "depth": 4,
      "text": "线程池线程数",
      "anchor": "线程池线程数",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%BA%BF%E7%A8%8B%E6%95%B0"
    },
    {
      "depth": 4,
      "text": "取消任务（终止线程）",
      "anchor": "取消任务终止线程",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%8F%96%E6%B6%88%E4%BB%BB%E5%8A%A1%E7%BB%88%E6%AD%A2%E7%BA%BF%E7%A8%8B"
    },
    {
      "depth": 4,
      "text": "Timer",
      "anchor": "timer",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#timer"
    },
    {
      "depth": 3,
      "text": "基于任务的异步模式(Task-based asynchronous pattern)",
      "anchor": "基于任务的异步模式task-based-asynchronous-pattern",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%9F%BA%E4%BA%8E%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%BC%82%E6%AD%A5%E6%A8%A1%E5%BC%8Ftask-based-asynchronous-pattern"
    },
    {
      "depth": 4,
      "text": "多线程编程要解决的问题",
      "anchor": "多线程编程要解决的问题",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%BC%96%E7%A8%8B%E8%A6%81%E8%A7%A3%E5%86%B3%E7%9A%84%E9%97%AE%E9%A2%98"
    },
    {
      "depth": 4,
      "text": "创建&启动任务",
      "anchor": "创建启动任务",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%88%9B%E5%BB%BA%E5%90%AF%E5%8A%A8%E4%BB%BB%E5%8A%A1"
    },
    {
      "depth": 4,
      "text": "取消任务",
      "anchor": "取消任务",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%8F%96%E6%B6%88%E4%BB%BB%E5%8A%A1"
    },
    {
      "depth": 4,
      "text": "TaskCreationOptions",
      "anchor": "taskcreationoptions",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#taskcreationoptions"
    },
    {
      "depth": 5,
      "text": "父子任务",
      "anchor": "父子任务",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E7%88%B6%E5%AD%90%E4%BB%BB%E5%8A%A1"
    },
    {
      "depth": 4,
      "text": "任务异常与状态判断",
      "anchor": "任务异常与状态判断",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E4%BB%BB%E5%8A%A1%E5%BC%82%E5%B8%B8%E4%B8%8E%E7%8A%B6%E6%80%81%E5%88%A4%E6%96%AD"
    },
    {
      "depth": 4,
      "text": "WhenAll 与 异步并行",
      "anchor": "whenall-与-异步并行",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#whenall-%E4%B8%8E-%E5%BC%82%E6%AD%A5%E5%B9%B6%E8%A1%8C"
    },
    {
      "depth": 4,
      "text": "WhenAny",
      "anchor": "whenany",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#whenany"
    },
    {
      "depth": 4,
      "text": "WaitAll 与 同步",
      "anchor": "waitall-与-同步",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#waitall-%E4%B8%8E-%E5%90%8C%E6%AD%A5"
    },
    {
      "depth": 4,
      "text": "延续任务",
      "anchor": "延续任务",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%BB%B6%E7%BB%AD%E4%BB%BB%E5%8A%A1"
    },
    {
      "depth": 5,
      "text": "ContinueWith",
      "anchor": "continuewith",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#continuewith"
    },
    {
      "depth": 5,
      "text": "TaskAwaiter",
      "anchor": "taskawaiter",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#taskawaiter"
    },
    {
      "depth": 4,
      "text": "async & await 与同步、异步",
      "anchor": "async-await-与同步异步",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#async-await-%E4%B8%8E%E5%90%8C%E6%AD%A5%E5%BC%82%E6%AD%A5"
    },
    {
      "depth": 3,
      "text": "实现一个既能同步又能异步执行的类",
      "anchor": "实现一个既能同步又能异步执行的类",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E6%97%A2%E8%83%BD%E5%90%8C%E6%AD%A5%E5%8F%88%E8%83%BD%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E7%9A%84%E7%B1%BB"
    },
    {
      "depth": 2,
      "text": "Ref",
      "anchor": "ref",
      "citation": "https://www.pystone.net/notes/csharp-multithreading/#ref"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:programming-languages-and-runtimes",
      "title": "编程语言与运行时",
      "url": "https://www.pystone.net/notes/programming-languages-and-runtimes/",
      "atlas": "https://www.pystone.net/?node=programming-languages-and-runtimes#knowledge-atlas",
      "label": "编程语言与运行时",
      "origin": "explicit",
      "humanReviewed": true,
      "context": ".NET与CSharp中的“C#多线程”导航项",
      "citation": "https://www.pystone.net/notes/programming-languages-and-runtimes/#net%E4%B8%8Ecsharp"
    }
  ],
  "contentMarkdown": "# C#多线程\n\n> 创建时间：2020/12/10 15:57\n\n  * C#多线程\n    * concepts\n      * Multitasking\n        * process\n        * Thread\n    * Multithreading in C Sharp\n      * Thread\n        * 状态\n        * 启动与参数传递\n          * 委托传参(需要装箱拆箱)\n          * 使用静态变量或类成员变量\n          * 委托 + 两层函数避免Boxing\n        * 阻塞（Block）\n        * 线程优先级、前台线程和后台线程\n      * 多线程竞争\n        * lock & Monitor 与线程锁\n        * 原子操作\n        * Mutex类与进程同步\n        * Semaphore（信号量）与资源池\n        * ReaderWriterLockSlim\n      * 线程间通信与同步\n        * AutoRestEvent, ManualResetEvent\n        * CountdownEvent 与 线程完成数\n        * Barrier 类\n        * 线程等待进阶\n      * ThreadPool 线程池\n        * ThreadPool 类\n        * 适用性\n        * 具体用法\n        * 线程池线程数\n        * 取消任务（终止线程）\n        * Timer\n      * 基于任务的异步模式(Task-based asynchronous pattern)\n        * 多线程编程要解决的问题\n        * 创建&启动任务\n        * 取消任务\n        * TaskCreationOptions\n          * 父子任务\n        * 任务异常与状态判断\n        * WhenAll 与 异步并行\n        * WhenAny\n        * WaitAll 与 同步\n        * 延续任务\n          * ContinueWith\n          * TaskAwaiter\n        * async & await 与同步、异步\n      * 实现一个既能同步又能异步执行的类\n    * Ref\n\n## concepts\n\n### Multitasking\n\nWindows operating system is a multitasking operating system. It means it has the ability to run multiple applications at the same time.\n\n#### process\n\nA process is a part of the operating system (or a component under the operating system) which is responsible for executing the program or application.\n\n![Alt text](assets/1607587474930.png)\n\nThere are also multiple processes that are running in the background which are known as the **background processes**. These background processes are known as windows services and the Operating system runs a lot of windows services in the background.\n\nSo, we have an **operating system** and under the operating system, we have **processes** that running our **applications**.\n\n#### Thread\n\nIn computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process.\n\nIn simple words, we can say that a Thread is a unit of a process that is responsible for executing the application code.\n\n## Multithreading in C Sharp\n\n### Thread\n\n#### 状态\n\n操作系统中进程的状态的常见表述：\n三种基本状态：就绪，运行，阻塞。\n实际系统中，为了管理的需要，还存在着另外两种状态：创建状态和终止状态。\n\n![Alt text](assets/1607591150344.png)\n\nvia: [Studytonight](https://www.studytonight.com/operating-system/operating-system-processes)\n\n  * NEW(创建，未启动状态)- The process is being created.\n\n  * READY（就绪状态）- The process is waiting to be assigned to a processor.\n\n  * RUNNING（运行）- Instructions are being executed.\n\n  * WAITING（阻塞，等待，不可运行状态）- The process is waiting for some event to occur(such as an I/O completion or reception of a signal).\n\n  * TERMINATED（终止，死亡状态）- The process has finished execution.\n\n* * *\n\nC#中的ThreadState图(仅供理解，不建议深究):\n\n![Alt text](assets/1607590249171.png)\n\n> Thread state is only of interest in debugging scenarios. Your code should never use thread state to synchronize the activities of threads.\n\nThreadState 是一个枚举，记录了线程的状态，我们可以从中判断线程的生命周期和健康情况。但是里面有很多枚举类型是没有用处的，我们可以使用一个这样的方法来获取更加有用的信息：\n\n```csharp\nstring s1 = &quot;Hello &quot;;\nstring s2 = s1;\ns1 += &quot;World&quot;;\n\nSystem.Console.WriteLine(s2);\n//Output: Hello\n\n```\n\n#### 启动与参数传递\n\n##### 委托传参(需要装箱拆箱)\n\n```csharp\nstring s1 = &quot;Hello &quot;;\nstring s2 = s1;\ns1 += &quot;World&quot;;\n\nSystem.Console.WriteLine(s2);\n//Output: Hello\n\n```\n\n##### 使用静态变量或类成员变量\n\n优点是不需要装箱拆箱，多线程可以共享空间；缺点是变量是大家都可以访问，此种方式在多线程竞价时，可能会导致多种问题(可以加锁解决)。\n\n```csharp\nstring s1 = &quot;Hello &quot;;\nstring s2 = s1;\ns1 += &quot;World&quot;;\n\nSystem.Console.WriteLine(s2);\n//Output: Hello\n\n```\n\n##### 委托 + 两层函数避免Boxing\n\n```csharp\nstring s1 = &quot;Hello &quot;;\nstring s2 = s1;\ns1 += &quot;World&quot;;\n\nSystem.Console.WriteLine(s2);\n//Output: Hello\n\n```\n\n#### 阻塞（Block）\n\n阻塞的定义：当线程由于特点原因暂停执行，那么它就是阻塞的。\n如果线程处于阻塞状态，线程就会交出他的 CPU 时间片，并且不会消耗 CPU 时间，直至阻塞结束。阻塞会发生上下文切换。\n\n  * Thread.Sleep() 方法可以将当前线程挂起一段时间\n\n  * Thread.Join() 方法可以阻塞当前线程一直等待另一个线程运行至结束。\n\n#### 线程优先级、前台线程和后台线程\n\nHighest > AboveNormal > Normal > BelowNormal > Lowest\n前台线程的优先级大于后台线程，并且程序需要等待所有前台线程执行完毕后才能关闭；而当程序关闭时，无论后台线程是否在执行，都会强制退出。\n\n### 多线程竞争\n\n> 关于同步和互斥：\n>  相交进程之间的关系主要有两种，同步与互斥。所谓互斥，是指散步在不同进程之间的若干程序片断，当某个进程运行其中一个程序片段时，其它进程就不能运行它 们之中的任一程序片段，只能等到该进程运行完这个程序片段后才可以运行。所谓同步，是指散步在不同进程之间的若干程序片断，它们的运行必须严格按照规定的 某种先后次序来运行，这种先后次序依赖于要完成的特定的任务。\n>  显然，同步是一种更为复杂的互斥，而互斥是一种特殊的同步。\n>  也就是说互斥是两个线程之间不可以同时运行，他们会相互排斥，必须等待一个线程运行完毕，另一个才能运行，而同步也是不能同时运行，但他是必须要安照某种次序来运行相应的线程（也是一种互斥）！\n>  总结：互斥：是指某一资源同时只允许一个访问者对其进行访问，具有唯一性和排它性。但互斥无法限制访问者对资源的访问顺序，即访问是无序的。\n>  同步：是指在互斥的基础上（大多数情况），通过其它机制实现访问者对资源的有序访问。在大多数情况下，同步已经实现了互斥，特别是所有写入资源的情况必定是互斥的。少数情况是指可以允许多个访问者同时访问资源。\n\n#### lock & Monitor 与线程锁\n\nlock 用于读一个引用类型进行加锁，同一时刻内只有一个线程能够访问此对象。锁可以阻止其它线程执行锁块(lock(o){})中的代码，当锁定时，其它线程必须等待锁中的线程执行完成并释放锁。\n\nlock 是语法糖，是通过 Monitor 来实现的。lock的用法及底层实现：\n\n```csharp\nstring s1 = &quot;Hello &quot;;\nstring s2 = s1;\ns1 += &quot;World&quot;;\n\nSystem.Console.WriteLine(s2);\n//Output: Hello\n\n```\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\nLock 锁定的对象，应该是 **静态的引用类型** （字符串除外）。\n\n> 锁不太适合I/O场景，例如文件I/O，繁杂的计算或者操作比较持久的过程，会给程序带来很大的性能损失。\n\n一般来说，lock关键字够用了，Monitor用法参见: <https://www.cnblogs.com/whuanle/p/12722853.html>\n\n#### 原子操作\n\n在接受到 **中断（Interrupt）** 的时候，CPU 必须要进行 **上下文交换（Context Switch）** 。进行上下文切换时，会带来性能损失。\n\n> 只有操作系统才能切换线程、挂起线程，因此阻塞线程是由操作系统处理的，这种方式被称为 **内核模式(kernel-mode)** 。\n\nInterlocked 类，为多个线程共享的变量提供原子操作。使用 Interlocked 类，可以在不阻塞线程(lock、Monitor)的情况下，避免竞争条件。\n更多信息参见：<https://www.cnblogs.com/whuanle/p/12724371.html>\n\n#### Mutex类与进程同步\n\nMutex 中文为互斥，Mutex 类叫做互斥锁。它还可用于进程间同步的同步基元。互斥锁(Mutex)，用于多线程中防止两条线程同时对一个公共资源进行读写的机制。\n\n> Mutex 跟 lock 相似，但是 Mutex 支持多个进程。Mutex 大约比 lock 慢 20 倍。\n\nWindows 操作系统中，Mutex 同步对象有两个状态：\n\n  * signaled：未被任何对象拥有；\n\n  * nonsignaled：被一个线程拥有；\n\nMutex 只能在获得锁的线程中，释放锁。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n更详细用法参见：<https://www.cnblogs.com/whuanle/p/12726724.html>\n\n#### Semaphore（信号量）与资源池\n\n限制同时访问某一资源或资源池的线程数。\n详见：<https://www.cnblogs.com/whuanle/p/12728416.html>\n\n#### ReaderWriterLockSlim\n\nReaderWriterLock 类：定义支持单个写线程和多个读线程的锁。\nReaderWriterLockSlim 类：表示用于管理资源访问的锁定状态，可实现多线程读取或进行独占式写入访问。\n两者的 API 十分接近， ReaderWriterLockSlim 相对更加安全。\n详细内容参见：<https://www.cnblogs.com/whuanle/p/12773894.html>\n\n### 线程间通信与同步\n\n#### AutoRestEvent, ManualResetEvent\n\n用于从一个线程向另一个线程发送通知。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n![Alt text](assets/1607597574530.png)\n\n* * *\n\nAutoResetEvent 和 ManualResetEvent 十分相似。两者之间的区别，在于前者是自动(Auto)，后者是手动(Manua)。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n#### CountdownEvent 与 线程完成数\n\nCountdownEvent Class\nRepresents a synchronization primitive that is signaled when its count reaches zero.\n设定一个计数器，每个线程完成后，就会减去 1 ，当计数器为 0 时，代表所有线程都已经完成了任务。\n\n需求: 假如，程序需要向一个 Web 发送 5 次请求，受网路波动影响，有一定几率请求失败。如果失败了，就需要重试。\n传统方法\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n使用CountdownEvent 实现：\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n#### Barrier 类\n\n![Alt text](assets/1607602967865.png)\n\n每个参与者完成阶段任务后后将被阻止继续执行，直至所有参与者都已达到同一阶段。\n\n情景: 假设有个比赛，一个有三个环节，有三个小组参加比赛。比赛有三个环节，小组完成一个环节后，可以去等待区休息，等待其他小组也完成比赛后，开始进行下一个环节的比赛。\n`new Barrier(int,Action)`设置有多少线程参与，Action 委托设置每个阶段完成后执行哪些动作。\n\n`.SignalAndWait()` 阻止当前线程继续往下执行；直到其他完成也执行到此为止。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n#### 线程等待进阶\n\n<https://www.cnblogs.com/whuanle/p/12783086.html>\n\n### ThreadPool 线程池\n\n![Alt text](assets/1607587813963.png)\n\n线程池全称为托管线程池，线程池受 .NET 通用语言运行时(CLR)管理，线程的生命周期由 CLR 处理，因此我们可以专注于实现任务，而不需要理会线程管理。\n\n#### ThreadPool 类\n\n一个应用程序最多只能有一个线程池；\n\nThreadPool 类是一个静态类，它提供一个线程池，该线程池可用于执行任务、发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。\n线程池维护一个请求队列， QueueUserWorkItem() 方法接受一个代表用户异步操作的委托(名为 WaitCallback )，调用此方法传入委托后，就会进入线程池内部队列中。\nWaitCallback 委托的定义如下：\n`public delegate void WaitCallback(object state);`\n\n  * 不要将长时间运行的操作放进线程池中；\n\n  * 不应该阻塞线程池中的线程；\n\n  * 线程池中的线程都是后台线程(又称工作者线程)；\n\n#### 适用性\n\n  * 线程池是为突然大量爆发的线程设计的，通过有限的几个固定线程为大量的操作服务， **减少了创建和销毁线程所需的时间** ，从而提高效率。\n\n  * ThreadPool适合于并发运行若干个运行时间不长且互不干扰的函数。\n\n* * *\n\nThreadPool中的线程不用手动开始，也不能手动取消，你要做的只是把工作函数排入线程池，剩下的工作由系统自动完成，也就是说我们不能控制线程池中的线程。\n在以下情况下 **不宜使用** ThreadPool类而应该使用单独的Thread类：\n\n  * 线程执行需要很长时间；\n\n  * 需要为线程指定详细的优先级；\n\n  * 在执行过程中需要对线程进行操作，比如睡眠，挂起等。\n\n#### 具体用法\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n> Environment.ProcessorCount 可以确定当前计算机上有多少个处理器数量(例如CPU是四核八线程，结果就是八)。\n\n#### 线程池线程数\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\nworkerThreads：要由线程池根据需要创建的新的最小工作程序线程数。\ncompletionPortThreads：要由线程池根据需要创建的新的最小空闲异步 I/O 线程数。\n\n#### 取消任务（终止线程）\n\n被启动的线程，每个阶段都判断 .IsCancellationRequested，然后确定是否停止运行。这取决于线程的自觉性。\n\n**这个取消，在于信号的发生和信号的捕获，任务的取消不是实时的。**\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n#### Timer\n\n  * System.Timers.Timer，它会定期触发一个事件并在一个或多个事件接收器中执行代码。\n\n  * System.Threading.Timer，它定期在线程池线程上执行一个回调方法。\n\nSystem.Threading.Timer 其中一个构造函数定义如下：\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\nallback：要定时执行的方法；\nstate：要传递给线程的信息(参数)；\ndueTime：延迟时间，避免一创建计时器，马上开始执行方法；\nperiod：设置定时执行方法的时间间隔；\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n### 基于任务的异步模式(Task-based asynchronous pattern)\n\n> .NET provides three patterns for performing asynchronous operations:\n>\n>   * 基于任务的异步模式( **TAP** , Task-based asynchronous pattern) - uses a single method to represent the initiation and completion of an asynchronous operation. ( **async** and **await** keywords )\n>\n>   * 基于事件的异步模式( **EAP** , Event-based Asynchronous Pattern) - 不推荐\n>\n>   * 异步编程模型模式( **APM** , Asynchronous Programming Model) - 不推荐\n>\n>\n\n#### 多线程编程要解决的问题\n\n  1. 传递数据和返回结果\n传递数据倒是没啥问题，只是难以获取到线程的返回值，处理线程的异常也需要技巧。\n\n  2. 监控线程的状态\n新建新的线程后，如果需要确定新线程在何时完成，需要自旋或阻塞等方式等待。\n\n  3. 线程安全\n设计时要考虑如果避免死锁、合理使用各种同步锁，要考虑原子操作，同步信号的处理需要技巧。\n\n  4. 性能\n玩多线程，最大需求就是提升性能，但是多线程中有很多坑，使用不当反而影响性能。\n\n#### 创建&启动任务\n\n* * *\n\nnew Task() & Start()启动 - 启动 Task，并将它安排到当前的 TaskScheduler 中执行。\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n* * *\n\nTask.Factory.StartNew()\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n* * *\n\nTask.Run()\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n当需要对长时间运行、计算限制的任务(计算密集型)进行精细控制时才使用 StartNew() 方法；\n官方推荐使用 Task.Run 方法启动计算限制任务。\nTask.Factory.StartNew() 可以实现比 Task.Run() 更细粒度的控制。\n\n#### 取消任务\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n#### TaskCreationOptions\n\n枚举 | Value | 说明\n---|---|---\nAttachedToParent | 4 | 指定将任务附加到任务层次结构中的某个父级。\nDenyChildAttach | 8 | 指定任何尝试作为附加的子任务执行的子任务都无法附加到父任务，会改成作为分离的子任务执行。\nHideScheduler | 16 | 防止环境计划程序被视为已创建任务的当前计划程序。\nLongRunning | 2 | 指定任务将是长时间运行的、粗粒度的操作，涉及比细化的系统更少、更大的组件。\nNone | 0 | 指定应使用默认行为。\nPreferFairness | 1 | 提示 TaskScheduler 以一种尽可能公平的方式安排任务。\nRunContinuationsAsynchronously | 64 | 强制异步执行添加到当前任务的延续任务。\n\n##### 父子任务\n\n父任务如果先执行完毕，那么必须等待子任务完成后，父任务才算完成。\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n#### 任务异常与状态判断\n\nTask类中描述任务字段的状态如下:\n\n  * IsCanceled\n\n  * IsCompleted\n\n  * IsCompletedSuccessfully\n\n  * IsFaulted 获取 Task是否由于未经处理异常的原因而完成。\n\n  * Status\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n![Alt text](assets/1607670556723.png)\n\n#### WhenAll 与 异步并行\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n#### WhenAny\n\nTask.WhenAll() 当所有任务都完成时，才算完成，而 Task.WhenAny() 只要其中一个任务完成，都算完成。\n\n```xml\npublic class AGenericClass&lt;T&gt; where T : IComparable&lt;T&gt; { }\n\n```\n\n#### WaitAll 与 同步\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\nTask.WaitAll() 其中一个重载方法的定义:\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\n  * millisecondsTimeout ：Int32\n等待的毫秒数，-1 表示无限期等待。\n\n  * cancellationToken ：CancellationToken\n等待任务完成期间要观察的 CancellationToken。\n\n#### 延续任务\n\n##### ContinueWith\n\n![Alt text](assets/1607671750908.png)\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\n##### TaskAwaiter\n\n等待异步任务完成的对象并为结果提供参数\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\n#### async & await 与同步、异步\n\n  1. async 告诉机器，调用这个函数，不需要等他执行完，即异步执行\n\n  2. await 用来标记一个task，告诉机器，执行到这行代码，需要等这个task完成。\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\n### 实现一个既能同步又能异步执行的类\n\n[《C#多线程(15)：任务基础③》](https://www.cnblogs.com/whuanle/p/12802943.html)一文中，使用TaskCompletionSource类型实现了一个实现一个支持同步和异步任务的类型，帮助读者理解TaskCompletionSource类。\n笔者认为，在学习知识的过程中，应当本着这样一个原则： **理解知识的本质原理，并且记忆的东西越少越好** 。这样有如下好处：\n\n  * 不容易混淆\n\n  * 减轻了记忆的负担\n\n  * 更有利于理解事物的本质\n\n而在实践的研发中，能用最简单的方式实现想要的效果是最好不过的。\n\n实现一个既能同步又能异步执行的类对我们理解同步异步的概念和原理很有帮助，是有必要的。因此，笔者使用最基本的Task类实现了相同的功能，这样反而更容易这个类的本质。\n\n```xml\npublic class UsingEnum&lt;T&gt; where T : System.Enum { }\npublic class UsingDelegate&lt;T&gt; where T : System.Delegate { }\npublic class Multicaster&lt;T&gt; where T : System.MulticastDelegate { }\n\n```\n\n## Ref\n\n<https://dotnettutorials.net/lesson/multithreading-in-csharp/>\n<https://en.wikipedia.org/wiki/Thread_pool>\n<https://www.cnblogs.com/whuanle/category/1756558.html>\n<https://blog.csdn.net/qq_33337811/article/details/72844254>\n<https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/>\n"
}
