Please look at the sample code below, When I place a break point inside "testmethod" and run the application, it is not hitting the breakpoint. Is this code good?
static void Main(string[] args)
{
Thread[] testthreads = new Thread[3];
List<int> testdata = new List<int>();
testdata.Add(1);
testdata.Add(2);
testdata.Add(3);
int i = 0;
foreach (int data in testdata)
{
testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
testthreads[i].Name = string.Format("Working Thread: {0}", data);
i++;
}
}
static void testmethod(int i)
{
try
{
//DataTable dt = DB.GetData(i);
if (dt.Count > 0)
{
Console.WriteLine("Count: {0}", dt.Count);
}
}
catch (Exception ex)
{
throw ex;
}
}
I tried another method and it always returns the Name of first input.
Method 2:
static void Main(string[] args) { List testdata = new List(); testdata.Add(111111); testdata.Add(222222); testdata.Add(333333);
foreach (int data in testdata)
{
new Thread(delegate()
{
DataTable dt = DB.GetData(data);
if (dt.Count > 0)
{
Console.WriteLine("Name: {0}", dt.Rows[0]["Name"];);
}
// Signal the CountdownEvent.
countdownEvent.Signal();
}).Start();
}
// Wait for workers.
countdownEvent.Wait();
Console.WriteLine("Finished.");
}
Output:
Name: JULIE
Name: JULIE
Name: JULIE
Always returns the value(Name) of 111111
You need to start the thread.
testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
testthreads[i].Name = string.Format("Working Thread: {0}", data);
testthreads[i].Start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With