日期:2014-05-17  浏览次数:20802 次

请教一个局部变量和lamda表达式的问题
直接举例吧

int i = 6;
ThreadPool.QueueUserWorkItem(state=>
{
    int j = (int)state +8;
},i)




int i = 6;
ThreadPool.QueueUserWorkItem(()=>
{
    int j = i+8;
})

的区别如何,哪种合理?
很多时候为了缩短代码量,用lamda写法,发现外部的变量也可以起作用,不需要作为参数传入,这样会不会出问题?

------解决方案--------------------
顶一楼,关于LZ 在4楼的问题,请自行反编译查看,相信你可以马上明白
------解决方案--------------------
能够访问 就能调用。不过 要注意一点 QueueUserWorkItem是异步的,外部变量可能会改变。
------解决方案--------------------
引用:
大家没明白我的意思,我的意思是,
Lamda表达式中的i变量是在Lamda之外定义的,他却可以无阻碍的直接调用,而不用通过参数的形式传递到Lamda里面去


是这样的,直接用,这就是他的魅力之一。
在多线程中,要先保存在一个临时变量中,否则会有安全问题。
以下在C# in a nutshell中的一段,给你参考

引用
Lambda expressions and captured variables
As we saw, a lambda expression is the most convenient and powerful way to pass
data to a thread. However, you must be careful about accidentally modifying captured
variables after starting the thread. For instance, consider the following:
for (int i = 0; i < 10; i++)
new Thread (() => Console.Write (i)).Start();
The output is nondeterministic! Here’s a typical result:
0223557799
The problem is that the i variable refers to the same memory location throughout
the loop’s lifetime. Therefore, each thread calls Console.Write on a variable whose
value may change as it is running! The solution is to use a temporary variable as
follows:
for (int i = 0; i < 10; i++)
{
int temp = i;
new Thread (() => Console.Write (temp)).Start();
}
Each of the digits 0 to 9 is then written exactly once. (The ordering is still undefined
because threads may start at indeterminate times.)
This