0
Answer

foreach loop lockup

Philip Bartlett

Philip Bartlett

16y
4.8k
1

I ran into a strange problem with a compact framework application last week and narrowed it done to the following code.

The program.cs code creates an instance of the singelton form and then calls Application.Run().  The form creates a worker thread that is implemented as part of a static class. The worker thread gets stuck in the foreach loop in WorkerThreadFunc() which blocks the main thread from finishing its initialization. I can avoid the problem by using a for loop in the thread, not using a singelton for the form, or initializing the thread from form.load() rather than the constructor.  Can someone please explain to me why this lockup occurs?

Philip

 

Program.cs

using System;

using System.Collections.Generic;

using System.Windows.Forms;

namespace LoggerUI

{

static class Program

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[MTAThread]

static void Main()

{

MainForm f = MainForm.Instance;

Application.Run(f);

}

}

}

 

ForEachLockup.cs:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace ForeachLockup

{

public partial class ForeachLockup : Form

{

private static ForeachLockup instance = new ForeachLockup();

public ForeachLockup()

{

Worker.Create();

Thread.Sleep(1000);

Worker.DoSomething();

InitializeComponent();

}

public static ForeachLockup Instance

{

get

{

return instance;

}

}

}

 

public class Worker

{

static Worker()

{

lstDummy = new List<int>();

for (int i = 0; i < 10; i++)

lstDummy.Add(i);

WorkerThread = new Thread(new ThreadStart(WorkerThreadFunc));

WorkerThread.Name = "WorkerThread";

WorkerThread.Priority = ThreadPriority.Normal;

WorkerThread.IsBackground = true;

WorkerThread.Start();

}

public static void Create()

{

}

public static int DoSomething()

{

lock (objLock)

{

return iDoSomething;

}

}

private static Thread WorkerThread;

private static List<int> lstDummy;

private static object objLock = new object();

private static int iDoSomething = 0;

private static void WorkerThreadFunc()

{

do

{

lock (objLock)

{

if (lstDummy != null && lstDummy.Count > 0)

{

foreach (int S in lstDummy) // Worker thread gets stuck here

{

iDoSomething++;

}

}

}

Thread.Sleep(0);

} while (true);

}

}

}