博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#多线程 线程池
阅读量:6967 次
发布时间:2019-06-27

本文共 1997 字,大约阅读时间需要 6 分钟。

实例1:直接看看微软提供的代码

using System;using System.Threading;public class Example{    public static void Main()    {        // Queue the task.        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));        Console.WriteLine("Main thread does some work, then sleeps.");        // If you comment out the Sleep, the main thread exits before        // the thread pool task runs.  The thread pool uses background        // threads, which do not keep the application running.  (This        // is a simple example of a race condition.)        Thread.Sleep(1000);        Console.WriteLine("Main thread exits.");    }    // This thread procedure performs the task.    static void ThreadProc(Object stateInfo)    {        // No state object was passed to QueueUserWorkItem, so         // stateInfo is null.        Console.WriteLine("Hello from the thread pool.");    }}

 

using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace Example{    class ThreadPoolDemo    {        // 用于保存每个线程的计算结果        static int[] result = new int[10];        //注意:由于WaitCallback委托的声明带有参数,        //所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。        static void Fun(object obj)        {            int n = (int)obj;            //计算阶乘            int fac = 1;            for (int i = 1; i <= n; i++)            {                fac *= i;            }            //保存结果            result[n] = fac;        }        static void Main(string[] args)        {            //向线程池中排入9个工作线程            for (int i = 1; i <= 9; i++)            {                //QueueUserWorkItem()方法:将工作任务排入线程池。                ThreadPool.QueueUserWorkItem(new WaitCallback(Fun), i);                // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。                // i   为传递给Fun方法的参数(obj将接受)。            }            //输出计算结果            for (int i = 1; i <= 9; i++)            {                Console.WriteLine("线程{0}: {0}! = {1}", i, result[i]);            }        }    }}

 

转载于:https://www.cnblogs.com/Sky-cloudless/p/4430992.html

你可能感兴趣的文章
普通程序员如何转向AI方向(转)
查看>>
Python是什么?
查看>>
从零开始山寨Caffe·拾:IO系统(三)
查看>>
Ubuntu下压缩解压文件
查看>>
入门指引 - PHP手册笔记
查看>>
java 调用启动远程shell脚本,启动spark
查看>>
Spring boot ----RestTemplate学习笔记
查看>>
[LUOGU] P3128 [USACO15DEC]最大流Max Flow
查看>>
windows2003server下能安装的MSN
查看>>
MyBatis和SpringMVC集成事务在Junit测试下有效但是在实际项目无效的问题
查看>>
Caffe将自己的文件生成lmdb
查看>>
C# 枚举中的位运算
查看>>
Codeforces Global Round 1 晕阙记
查看>>
相机相册
查看>>
百度文化秘籍
查看>>
VSTO Office二次开发对PPT自定义任务窗格测试
查看>>
Algs4-1.3.33一个双向队列Deque-双向链表实现
查看>>
Algs4-2.2.29自然的归并排序(未解决)
查看>>
Python学习——模块的基本知识
查看>>
iOS开发UI篇—ios应用数据存储方式(XML属性列表-plist)
查看>>