前言
多线程是c#中一个重要的概念,多线程指的是在同一进程中同时运行多个线程的机制。多线程适用于需要提高系统并发性、吞吐量和响应速度的场景,可以充分利用多核处理器和系统资源,提高应用程序的性能和效率。
多线程常用场景
- cpu 密集型任务.
- i/o 密集型任务.
- 并发请求处理.
- 大数据处理等.
什么是进程?
进程(process)是计算机中的一个执行中的程序,它是对正在运行的程序的抽象。一个进程包括了程序的代码、数据、堆栈以及其他操作系统所需的资源。
什么是线程?
线程(thread)是进程中的一个执行单元,一个进程可以包含多个线程,它们共享进程的资源,但拥有独立的执行流程。
使用 thread 类
public static void threadmethod() { var newthread = new thread(workermethod); newthread.start(); for (int i = 0; i < 8; i++) { console.writeline($"threadmethod 主线程开始工作:{i}"); thread.sleep(100); } } private static void workermethod() { for (int i = 0; i < 8; i++) { console.writeline($"workermethod 辅助线程开始工作:{i}"); thread.sleep(100); } }
使用 threadpool 类
public static void threadpoolmethod() { threadpool.queueuserworkitem(o => workermethod()); for (int i = 0; i < 8; i++) { console.writeline($"threadpoolmethod 主线程开始工作:{i}"); thread.sleep(100); } } private static void workermethod() { for (int i = 0; i < 8; i++) { console.writeline($"workermethod 辅助线程开始工作:{i}"); thread.sleep(100); } }
使用 task 类
public static void taskmethod() { task.run(() => workermethod()); for (int i = 0; i < 8; i++) { console.writeline($"taskmethod 主线程开始工作:{i}"); task.delay(100).wait(); } } private static void workermethod() { for (int i = 0; i < 8; i++) { console.writeline($"workermethod 辅助线程开始工作:{i}"); thread.sleep(100); } }
使用 parallel 类
public static void parallelmethod() { parallel.invoke(workermethod, workermethodother1, workermethodother2); } private static void workermethod() { for (int i = 0; i < 8; i++) { console.writeline($"workermethod 辅助线程开始工作:{i}"); thread.sleep(100); } } private static void workermethodother1() { for (int i = 0; i < 8; i++) { console.writeline($"workermethodother1 辅助线程开始工作:{i}"); thread.sleep(100); } } private static void workermethodother2() { for (int i = 0; i < 8; i++) { console.writeline($"workermethodother2 辅助线程开始工作:{i}"); thread.sleep(100); } }
到此这篇关于c#实现多线程的几种方式小结的文章就介绍到这了,更多相关c#实现多线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论