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

  • 相关阅读:
    ConfigurationManager读取dll的配置文件
    计算机常用英语词汇
    Com与.Net互操作
    C#创建COM组件供VB,PB,Delphi调用
    程序员的自我修养
    .NET Remoting三种信道Http,Tcp,IPC和Web Service的访问速度比较(转)
    .NET Remoting与Socket、Webservice和WCF的比较及优势 (转)
    .NET Remoting 入门实例
    关于Assembly.LoadFrom和Assembly.LoadFile的区别
    大数据处理中必不可少的概念
  • 原文地址:https://www.cnblogs.com/aoximin/p/13213443.html
Copyright © 2011-2022 走看看