c# - 为什么生成线程时会出现意外输出?

标签 c# .net multithreading

我试图产生一定数量的线程。但是当我将参数传递给函数时,输出是随机的。它多次选择变量“i”的一些值并忽略一些。我是 C# 的新手。如果我做错了什么,请解释。

using System;
using System.Threading;

public class first
{
     public static void tone(int i)
{
        Console.WriteLine("Hi ! this is thread : {0} ",i);
        Thread.Sleep(10);
}

public static void Main(String[] args)
{
    int i;
    for (i = 0; i < 10; i++)
    {
        Thread th1 = new Thread(()=>tone(i) );
        th1.Start();
       // Console.WriteLine(i);
    }
    Console.WriteLine("hey there!");
    Console.ReadLine();
}

enter image description here

最佳答案

因为closure :

将您的代码更改为:

int i;
    for (i = 0; i < 10; i++)
    {
       int j = i;
        Thread th1 = new Thread(()=>tone(j) );
        th1.Start();
       // Console.WriteLine(i);
    }

关于c# - 为什么生成线程时会出现意外输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23735861/

相关文章:

c# - Xamarin.Forms-为什么 NavigationPage 的 CustomRenderer Android 抛出 InvalidCastException?

c# - AutoMapper 中 IValueFormatter 的替代方案是什么?

.net - 以编程方式识别 Excel 版本

c# - WPF 数据网格行数据绑定(bind)?

c# - 重构 If 语句

c++ - Qt 如何从运行的线程更新主窗口,正确的方法

android - 如何使用线程更新进度条

c# - 将数据从 C# 传递到 jQuery

c# - C#中段落编号的正则表达式

.net - 类库中的 WebBrowser 控件