相关疑难解决方法(0)

C#中循环中的捕获变量

我遇到了一个关于C#的有趣问题.我有如下代码.

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(() => variable * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}
Run Code Online (Sandbox Code Playgroud)

我希望它输出0,2,4,6,8.但是,它实际输出5个10.

似乎是由于所有操作都涉及一个捕获的变量.结果,当它们被调用时,它们都具有相同的输出.

有没有办法解决这个限制,让每个动作实例都有自己的捕获变量?

c# closures captured-variable

202
推荐指数
7
解决办法
5万
查看次数

循环操作列表

我无法理解如何遍历Action列表.当我尝试它时,我最终得到的值与前一次迭代相同.

这是代码(简化示例):

string[] strings = { "abc", "def", "ghi" };

var actions = new List<Action>();
foreach (string str in strings)
    actions.Add(new Action(() => { Trace.WriteLine(str); }));

foreach (var action in actions)
    action();
Run Code Online (Sandbox Code Playgroud)

输出:

ghi
ghi
ghi
Run Code Online (Sandbox Code Playgroud)

为什么在strings执行操作时始终选择最终元素?
我怎样才能实现所需的输出:

abc
def
ghi
Run Code Online (Sandbox Code Playgroud)

c# action enumeration

8
推荐指数
2
解决办法
9179
查看次数

你如何在C#中获得正在运行的线程列表?

我在C#中创建动态线程,我需要获取那些运行线程的状态.

List<string>[] list;
list = dbConnect.Select();

for (int i = 0; i < list[0].Count; i++)
{
    Thread th = new Thread(() =>{
        sendMessage(list[0]['1']);
        //calling callback function
    });
    th.Name = "SID"+i;
    th.Start();
}

for (int i = 0; i < list[0].Count; i++)
{
    // here how can i get list of running thread here.
}
Run Code Online (Sandbox Code Playgroud)

如何获得正在运行的线程列表?

c# multithreading threadpool

6
推荐指数
3
解决办法
3万
查看次数