zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

c#多线程 注意 传值 地方
2023-09-14 09:01:09 时间

前言

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

正文

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,如果值是变量,那么我们应该考虑的是方法在线程开始的时候变量是否产生变化。