跟进:
如果我使用本地范围的变量运行函数,我的程序最终只会丢弃该值 - 这让我完全困惑。
为什么会这样?
简单示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> Dict = new Dictionary<string, object>() {
{ "1", new Dictionary<string, object>() {
{"Columns",new object[1]{ "name"} }
}},
{ "2", new Dictionary<string, object>() {
{"Columns",new object[1]{ "name"} }
}}
};
int i = 0;
foreach (KeyValuePair<string, object> record in Dict)
{
var _recordStored = record; //THIS IS(was) SUPPOSED TO FIX MY WOES!!!
new System.Threading.Timer(_ => {
i++;
//if i comment the next line, the code "works" ( albeit doing nothing really" )
processFile((Dictionary<string, object>)_recordStored.Value, new List<object>{});
Console.WriteLine("Val: " + _recordStored.Key + " ThreadID: " + System.Threading.Thread.CurrentThread.ManagedThreadId+ " "+ i);
}, null, TimeSpan.Zero, new TimeSpan(0, 0,0,0,1));
}
for (; ; )
{
System.Threading.Thread.Sleep(10000);
}
}
public static void processFile(Dictionary<string, dynamic> record, List<object> fileData)
{
DataTable dt = new DataTable("table");
foreach (string column in record["Columns"])
{
dt.Columns.Add(column, typeof(string));
}
}
}
}
哪个有输出:
Val: 1 ThreadID: 12
Val: 2 ThreadID: 11
Val: 1 ThreadID: 11
Val: 2 ThreadID: 12
Val: 2 ThreadID: 12
Val: 1 ThreadID: 11
Val: 2 ThreadID: 12
但最终(大约 880 次之后)迭代会开始打印
Val: 2 ThreadID: 10
Val: 2 ThreadID: 12
Val: 2 ThreadID: 10
Val: 2 ThreadID: 12
Val: 2 ThreadID: 10
Val: 2 ThreadID: 12
这一切最奇怪的是,当我删除对processFile
代码的调用时,它总是会完美执行。