Lambda表达式在C#多线程 [英] Lambda expressions with multithreading in C#
本文介绍了Lambda表达式在C#多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想明白为什么这个程序不能正常工作
预计产量:以任意顺序$ B $ 0-19号b口得到什么,当我运行:一些数字重复,有时20印刷
请帮忙。我试图在DoSomething的()锁(OBJ),但它并没有帮助。
程序
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用的System.Threading;
命名空间ConsoleApplication2
{
公众委托无效callbackDelegate(INT X);
类节目
{
无效processCallback(INT X)
{
Console.WriteLine(回调:我得到的值是+ x)的;
}
静态无效的主要(字串[] args)
{
程序P =新计划();
p.processinThreads();
Console.ReadKey();
}
公共无效DoSomething的(INT X,callbackDelegate回调)
{
Thread.sleep代码(1000);
//Console.WriteLine(\"I刚睡醒现在的+ X);
回调(X);
}
公共无效processinThreads()
{
的for(int i = 0; I< 20;我++)
{
线程t =
新主题(新的ThreadStart(()=> DoSomething的(I,processCallback)));
t.Start();
}
}
}
}
解决方案
公共无效processinThreads()
{
的for(int i = 0; I< 20;我++)
{
INT本地= I;
线程t =新主题(新的ThreadStart(()=> DoSomething的(本地,processCallback)));
t.Start();
}
}
您的问题涉及到封闭过的lambda。
I am trying to understand why this program doesn't work
Expected output: numbers 0-19 in random order What I get when I run: some numbers repeat, sometimes 20 is printed.
Please help. I tried with lock(obj) in DoSomething() but it didn't help.
Program
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();
}
}
}
}
解决方案
public void processinThreads()
{
for (int i = 0; i < 20; i++)
{
int local = i;
Thread t = new Thread(new ThreadStart(()=>DoSomething(local, processCallback)));
t.Start();
}
}
Your problem is related to closure over lambda.
这篇关于Lambda表达式在C#多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文