【发布时间】:2012-02-23 12:01:05
【问题描述】:
我试图了解为什么这个程序不起作用
预期输出:随机顺序的数字 0-19 我运行时得到的结果:一些数字重复,有时会打印 20。
请帮忙。我尝试在 DoSomething() 中使用 lock(obj) 但没有帮助。
程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
public delegate void callbackDelegate(int x);
class Program
{
void processCallback(int x)
{
Console.WriteLine("IN callback: The value I got is " + x);
}
static void Main(string[] args)
{
Program p = new Program();
p.processinThreads();
Console.ReadKey();
}
public void DoSomething(int x, callbackDelegate callback)
{
Thread.Sleep(1000);
//Console.WriteLine("I just woke up now " + x);
callback(x);
}
public void processinThreads()
{
for (int i = 0; i < 20; i++)
{
Thread t =
new Thread(new ThreadStart(()=>DoSomething(i, processCallback)));
t.Start();
}
}
}
}
【问题讨论】:
-
C# Captured Variable In Loop 的可能重复项
-
对,我在搜索这个问题时找不到这个。好吧,我不知道这个“关闭 lambda 问题”:)
-
避免手动创建线程。 Here 详细解释了基准原因
标签: c# multithreading lambda