C#开启线程的四种示例
作者:zls365 时间:2022-06-01 13:04:37
1.异步委托开启线程
public class Program
{
public static void Main(string[] args)
{
Action<int, int> a = add;
a.BeginInvoke(3, 4, null, null);
Console.WriteLine("执行线程");
Console.ReadKey();
}
static void add(int a, int b)
{
Console.WriteLine(a + b);
}
}
2.通过Thread类开启线程
public class Program
{
public static void Main(string[] args)
{
Thread t1;
Thread t2;
t1 = new Thread(SetInfo1);
t2 = new Thread(SetInfo2);
t1.Start();
//线程睡眠
//t1.Join(1000);
//挂起线程
t1.Suspend();
//继续执行线程
t1.Resume();
//结束线程
//t1.Abort();
t2.Start();
Console.ReadKey();
}
//奇数线程
public static void SetInfo1()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 != 0)
{
Console.WriteLine("奇数为" + i);
}
}
}
//偶数线程
public static void SetInfo2()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
Console.WriteLine("偶数为" + i);
}
}
}
}
3.通过线程池开启线程
//线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池;每排入一个工作函数,就相当于请求创建一个线程;
//线程池的作用:
//1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
//2、如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止
public class Program
{
public static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "hjh" });
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
string[] arry = state as string[];//传过来的参数值
int workerThreads = 0;
int CompletionPortThreads = 0;
ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads);
Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads);
}
}
4.通过任务Task开启线程
public class Program
{
public static void Main(string[] args)
{
Task task = new Task(DownLoadFile_My);
task.Start();
Console.ReadKey();
}
static void DownLoadFile_My()
{
Console.WriteLine("开始下载...线程ID:"+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("下载完成!");
}
}
来源:https://www.cnblogs.com/zyr365/archive/2020/10/10/13794264.html
标签:c#,开启,线程
0
投稿
猜你喜欢
Java中new关键字和newInstance方法的区别分享
2022-12-04 03:12:52
SpringFramework应用接入Apollo配置中心过程解析
2021-08-30 09:03:50
C++中的运算符重载详解
2022-03-22 07:20:13
java多种幻灯片切换特效(经典)
2022-08-05 23:18:22
java编程小白进阶包的作用详解
2022-01-22 05:15:24
Android自定义ViewGroup实现标签浮动效果
2021-12-28 20:20:29
C#使用listView增删操作实例
2023-03-25 12:34:52
Android中悬浮窗口的实现原理实例分析
2021-07-11 07:34:07
在Maven下代理服务器设定的方式
2023-10-15 02:17:13
Android注解基础介绍快速入门与解读
2023-04-30 22:32:19
mybatis水平分表实现动态表名的项目实例
2023-04-02 22:11:42
Android 配置gradle实现VersionCode自增实例
2021-07-03 12:39:23
C#任务并行Parellel.For和Parallel.ForEach
2022-04-19 22:07:58
C#实现简单订单管理程序
2023-04-08 08:26:34
Android手机抓包步骤
2022-05-03 18:15:59
C# 拼图魔方小游戏
2023-10-27 20:41:22
android 自定义圆角button效果的实例代码(自定义view Demo)
2022-07-13 11:35:09
基于Springboot+Junit+Mockito做单元测试的示例
2023-01-03 21:15:51
c# 通过WinAPI播放PCM声音
2021-10-22 12:35:18
java发起http请求调用post与get接口的方法实例
2022-12-28 23:22:58