In my app I am running a method that takes few seconds to run and I need to fire that multiple times with different parameters to achieve what I want. Later on I started having performance problems and decided to fire those actions in multiple threads to reduce the time spent for running it. I implemented everything as expected, but when it comes for firing that thread it just freezes. It says threads are running, but never finishes. I thought maybe my methods that I am calling in threads are locking the same object and that is causing the threads to freeze, but it seems that is not the issue.
Here is a sample code:
public abstract class ModelBase
{
public static void RunInMultiThread(List<Action> actions)
{
Action testAction = new Action(() =>
{
Console.WriteLine("Other test");
});
List<Thread> threads = new List<Thread>();
foreach (Action action in actions)
{
ThreadStart dlg = () => { action(); };
Thread thread = new Thread(dlg);
thread.Start();
threads.Add(thread);
}
bool anyAlive = true;
while (anyAlive)
{
anyAlive = threads.Any(t => t.IsAlive);
}
}
}
/// <summary>
/// This class is autogenerated
/// </summary>
public class Model : ModelBase
{
public void FireActions()
{
List<Action> actions = new List<Action>();
for (int i = 1; i <= 100; i++)
{
Action action = new Action(() => { DoSomething(i); });
actions.Add(action);
}
RunInMultiThread(actions);
}
public void DoSomething(int a)
{
Console.WriteLine("Test " + a);
}
}
I am creating the new instance of the Model class and calling the FireActions
method. I can see the list of threads in the RunInMultiThread()
method and it says all the tasks are running. I don't see anything in the output.
To make it simpler, I passed the testAction
action to the ThreadStart
and that worked. I am very surprised why it doesn't work if I pass the actions that came in the list?
NOTE: The Model
class is actually autogenerated and located on another library and it's .NET version is 4.0. That library is built using the System.CodeDom.Compiler
. ModelBase
class is on another project and it's .NET version is 4.7.1.
Any ideas why it won't run my actions that is passed though the list??