c# 多线程传值注意的地方

前言

下面介绍多线程传值的几种方式,并说明注意点。

正文

static void Main(string[] args)
{
	SampleTread thead = new SampleTread(10);

	var theadone = new Thread(thead.CountNumbers);
	theadone.Start();
	theadone.Join();
	Console.WriteLine("---------------------");
	var threadTwo = new Thread(Count);
	threadTwo.Name = "TheadTwo";
	threadTwo.Start(8);
	threadTwo.Join();
	Console.WriteLine("---------------------");
	var ThreadThree = new Thread(() => CountNumbers(12));
	ThreadThree.Name = "ThreadThree";
	ThreadThree.Start();
	ThreadThree.Join();
	Console.WriteLine("------------------");
	int i = 10;
	var threadFour = new Thread(() => printNumber(i));
	i = 20;
	var threadFive = new Thread(() => printNumber(i));
	threadFour.Start();
	threadFive.Start();
}

static void Count(object iterations)
{
	CountNumbers((int)iterations);
}
static void CountNumbers(int iterations)
{
	for (int i = 0; i < iterations; i++)
	{
		Thread.Sleep(TimeSpan.FromSeconds(0.5));
		Console.WriteLine($"{Thread.CurrentThread.Name}print{i}");
	}
}
static void printNumber(int number)
{
	Console.WriteLine(number);
}
class SampleTread
{
	private readonly int _iterations;
	public SampleTread(int iterations)
	{
		this._iterations = iterations;
	}
	public void CountNumbers()
	{
		for (int i = 0; i < _iterations; i++)
		{
			Thread.Sleep(TimeSpan.FromSeconds(0.5));
			Console.WriteLine($"{ Thread.CurrentThread.Name}print{i}");
		}
	}
}

上文介绍了两种方式,一种是在thread的实例化时候传递的,另一种是在start 的时候传递的。

一个参数是const,而另一种参数是变量,对比这两种方式的不同。

可以跑一下是否和心中所想的是否一样。

注意点

一切运行的时候应该以start值为主:

int i = 10;
var threadFour = new Thread(() => printNumber(i));
i = 20;
var threadFive = new Thread(() => printNumber(i));
threadFour.Start();
threadFive.Start();

打印的结果都是20,如果值是变量,那么我们应该考虑的是方法在线程开始的时候变量是否产生变化。

posted @   敖毛毛  阅读(262)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示