Net之多线程用法
1.多线程
2.线程池
3.Task
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics; namespace MyThreads
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void TestMethod()
{
int sum = 0;
for (int i = 1; i < 100; i++)
{
sum += i;
}
Console.WriteLine("TestMethod当前线程的Id={0},sum= {1}", Thread.CurrentThread.ManagedThreadId, sum);
}
private void TestThread(string name)
{
int sum = 0;
for (int i = 1; i < 100; i++)
{
sum += i;
}
Console.WriteLine("{0}当前线程的Id={1},sum= {2}", name,Thread.CurrentThread.ManagedThreadId, sum);
}
private void brtThread_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("这里是单线程");
for (int i = 0; i < 5; i++)
{
TestMethod();
}
}
private void brtMutriThread_Click(object sender, RoutedEventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("这里是多线程");
Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
List<Thread> threadList = new List<Thread>();
ThreadStart threadStart = () => TestMethod();
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(threadStart);
threadList.Add(thread);
thread.Start();
}
threadList.ForEach(t => t.Join());
Console.WriteLine(string.Format("brtMutriThread_Click已结束,可以执行其他动作当前线程的id={0}",
Thread.CurrentThread.ManagedThreadId));
sw.Stop();
Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
} private void brtThreadPool_Click(object sender, RoutedEventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("这里是多线程");
Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
//线程池
//ThreadPool.QueueUserWorkItem(t => TestThread("ThreadPool1"));
//ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool2");
//ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool3");
//ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool4");
//ThreadPool.QueueUserWorkItem(t => TestThread(t.ToString()), "ThreadPool5"); using (ManualResetEvent m1 = new ManualResetEvent(false))
using (ManualResetEvent m2 = new ManualResetEvent(false))
using (ManualResetEvent m3 = new ManualResetEvent(false))
using (ManualResetEvent m4 = new ManualResetEvent(false))
using (ManualResetEvent m5 = new ManualResetEvent(false))
{
ThreadPool.QueueUserWorkItem(t => {
TestThread("ThreadPool1");
m1.Set();
});
ThreadPool.QueueUserWorkItem(t => {
TestThread("ThreadPool2");
m2.Set();
});
ThreadPool.QueueUserWorkItem(t =>
{
TestThread("ThreadPool3");
m3.Set();
});
ThreadPool.QueueUserWorkItem(t =>
{
TestThread("ThreadPool4");
m4.Set();
});
ThreadPool.QueueUserWorkItem(t =>
{
TestThread("ThreadPool5");
m5.Set();
});
m1.WaitOne();
m2.WaitOne();
m3.WaitOne();
m4.WaitOne();
m5.WaitOne();
}
Console.WriteLine(string.Format("brtMutriThread_Click已结束,可以执行其他动作当前线程的id={0}",
Thread.CurrentThread.ManagedThreadId));
sw.Stop();
Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
}
// task本质是基于线程池的,只是API被强化
private void brnTask_Click(object sender, RoutedEventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("这里是多线程");
Console.WriteLine(string.Format("当前线程的id:{0}", Thread.CurrentThread.ManagedThreadId));
//Task
List<Task> taskList = new List<Task>();
TaskFactory taskFactory = new TaskFactory();
for (int i = 0; i < 5;i++ )
{
taskList.Add(taskFactory.StartNew(() => TestThread("Task")));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine(string.Format("brnTask_Click已结束,可以执行其他动作当前线程的id={0}",
Thread.CurrentThread.ManagedThreadId));
sw.Stop();
Console.WriteLine("总耗时{0}", sw.ElapsedMilliseconds);
}
}
}
<Window x:Class="MyThreads.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="350">
<Grid>
<Button Content="单线程" Height="23" HorizontalAlignment="Left" Margin="108,63,0,0" Name="brtThread" VerticalAlignment="Top" Width="75" Click="brtThread_Click" />
<Button Content="多线程" Height="23" HorizontalAlignment="Left" Margin="108,112,0,0" Name="brtMutriThread" VerticalAlignment="Top" Width="75" Click="brtMutriThread_Click" />
<Button Content="线程池" Height="23" HorizontalAlignment="Left" Margin="108,168,0,0" Name="brtThreadPool" VerticalAlignment="Top" Width="75" Click="brtThreadPool_Click" />
<Button Content="Task" Height="23" HorizontalAlignment="Left" Margin="108,216,0,0" Name="brnTask" VerticalAlignment="Top" Width="75" Click="brnTask_Click" />
</Grid>
</Window>

Net之多线程用法的更多相关文章
- 转载 Android 多线程处理之多线程用法大集合
handler.post(r)其实这样并不会新起线程,只是执行的runnable里的run()方法,却没有执行start()方法,所以runnable走的还是UI线程. 1.如果像这样,是可以操作ui ...
- Android 多线程处理之多线程用法大集合
handler.post(r)其实这样并不会新起线程,只是执行的runnable里的run()方法,却没有执行start()方法,所以runnable走的还是UI线程. 1.如果像这样,是可以操作ui ...
- Android 多线程处理之多线程用法
handler.post(r)其实这样并不会新起线程,只是执行的runnable里的run()方法,却没有执行start()方法,所以runnable走的还是UI线程. 1.如果像这样,是可以操作ui ...
- 最全面的Java多线程用法解析
1.创建线程 在Java中创建线程有两种方法:使用Thread类和使用Runnable接口.在使用Runnable接口时需要建立一个Thread实例.因此,无论是通过Thread类还是Runnable ...
- Asp.Net多线程用法1
Asp.Net多线程简单用法 一个web页面 default.aspx 里面有两个控件GridView1,GridView2,通过两个线程分别加载绑定数据. protected void Page_L ...
- Android ——多线程处理之多线程用法大集合(转)
原文地址:http://blog.csdn.net/jie1991liu/article/details/16961701 另一篇地址:http://blog.sina.com.cn/s/blog_7 ...
- python多线程用法及与单线程耗时比较
下面,通过一个简单的例子,来把多线程和单线程执行任务的耗时做个比较 import time import threading # 音乐播放器 def music(func, loop): for i ...
- qt中多线程用法总结
1.多线程的理解 在操作系统中线程和进程划分. 操作系统可以同时执行多个任务,每个任务就是进程:进程可以同时执行多个任务,每个任务就是线程. 线程之间相互独立,抢占式执行.对于单核CPU来说同一时刻只 ...
- C#基础系列——多线程的常见用法详解
前言:前面几节分别介绍了下C#基础技术中的反射.特性.泛型.序列化.扩展方法.Linq to Xml等,这篇跟着来介绍下C#的另一基础技术的使用.最近项目有点紧张,所以准备也不是特别充分.此篇就主要从 ...
随机推荐
- python基础2-静态方法和类方法
1. 类方法 是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数,但是 ...
- synchronized类锁,对象锁,方法锁
synchronized从语法的维度一共有3个用法: 静态方法加上关键字 实例方法(也就是普通方法)加上关键字 方法中使用同步代码块 前两种方式最为偷懒,第三种方式比前两种性能要好. synchron ...
- iOS中属性 (nonatomic, copy, strong, weak)的使用 By hL
以下内容来自Stackflow的详解 1.Nonatomicnonatomic is used for multi threading purposes. If we have set the non ...
- sbt修改源(国内优先)
[repositories] local aliyun: https://maven.aliyun.com/repository/public oschina: http://maven.oschin ...
- traceback.print_exc()的用法
Python使用traceback.print_exc()来代替print e 来输出详细的异常信息 [python] view plain copy try: 1/0 except Except ...
- python基础语法_字符串编码
Python常用字符编码 http://www.cnblogs.com/schut/p/8406897.html Python常见字符编码间的转换 在字符串写入文件时,有时会因编码问题导致无法 ...
- MybatisPlus二级缓存
一.序言 本文承接[Mybatis缓存体系探究],提供基于MybatisPlus技术可用于生产环境下的二级缓存解决方案. 1.前置条件 掌握MyBatis二级缓存的原理 有关MyBatis缓存原理内容 ...
- 关于IDA无法从symbol server下载pdb的问题
在ida目录下,symsrv.dll同目录下创建一个symsrv.yes文件. symsrv.yes将可下载: symsrv.no将失败: 没有相关文件将会弹出授权询问,选择yes和no将创建对应文件 ...
- simulink模块执行顺序
1.simulink各模块执行顺序 Simulink模块的执行顺序都是序贯进行的,也就是沿着信号的流向进行.没有输入的模块先进行计算,更新状态量与输出,需要输入信号的模块等到输入信号准备ready之后 ...
- 多图|一文详解Nacos参数!
Nacos 中的参数有很多,如:命名空间.分组名.服务名.保护阈值.服务路由类型.临时实例等,那这些参数都是什么意思?又该如何设置?接下来我们一起来盘它. 1.命名空间 在 Nacos 中通过命名空间 ...