我有一个在线程中运行进程的类,每当我尝试对类的 List 属性使用 IEnumerable 方法时,它会将列表清零或使其为空。我的其他类属性保留其值。我尝试过其他类型的 IEnumerable 派生类,包括 ConcurrentQueue 和 ConcurrentStack,所有派生类似乎都有同样的问题。我已经尝试研究了几天,但无济于事。在这里的任何帮助将不胜感激。
namespace ThreadProblem
{
public class TestMyClass
{
public void StartTest()
{
MyClass testX = new MyClass(new List<BuildParam>() { BuildParam.value1, BuildParam.value2, BuildParam.value3 },"These are great comments");
testX.TestThread();
Console.WriteLine("testX has {0} members in the Build Parameters list",testX.BuildParameters.Count());
}
}
public class MyClass
{
public List<BuildParam> BuildParameters { get; set; }
public string Comments { get; set; }
public MyClass(List<BuildParam> parameters, string comments)
{
BuildParameters = parameters;
Comments = comments;
}
public void TestThread()
{
Thread testThread = new Thread(new ThreadStart(executeProcess));
testThread.Start();
Thread testThread2 = new Thread(new ThreadStart(executeProcess2));
testThread2.Start();
}
void executeProcess()
{
try
{
Console.WriteLine("Calling process containing IEnumerable extension method - Parameter count {0}", BuildParameters.Count());
Console.WriteLine("Calling process containing IEnumerable extension method - Comments: {0}", Comments);
//here is what seems to cause the issue....
string paramsList = String.Format("Calling process containing IEnumerable extension method - These parameters will be used: {0}", String.Join(", ", BuildParameters.Select(t => t.ToString())));
foreach (var item in BuildParameters)
{
//do something
Console.WriteLine("Calling process containing IEnumerable extension method - Howdy, I am {0}", item.ToString());
}
Console.WriteLine("Calling process containing IEnumerable extension method - Comments Again: {0}", Comments);
}
catch (Exception ex)
{
throw ex;
}
}
void executeProcess2()
{
try
{
Console.WriteLine("Calling process not containing IEnumerable extension method - Comments: {0}", Comments);
foreach (var item in BuildParameters)
{
//do something
Console.WriteLine("Calling process not containing IEnumerable extension method - Hi, I am {0}", item.ToString());
}
Console.WriteLine("Calling process not containing IEnumerable extension method - Comments again: {0}", Comments);
}
catch (Exception ex)
{
throw ex;
}
}
}
public enum BuildParam
{
value1,
value2,
value3
}
}
这会产生类似于以下的输出:
Calling process not containing IEnumerable extension method - Comments: These are great comments
testX has 3 members in the Build Parameters list
Calling process not containing IEnumerable extension method - Hi, I am value1
Calling process not containing IEnumerable extension method - Hi, I am value2
Calling process not containing IEnumerable extension method - Hi, I am value3
Calling process not containing IEnumerable extension method - Comments again: These are great comments
Calling process containing IEnumerable extension method - Parameter count 3
Calling process containing IEnumerable extension method - Comments: These are great commentscomments