I have the following C# code snippet in which I have simulated my problem. In this program I have a Service function that call ReadRooms method.
Now I am calling the service method on different threads. I was expecting that both ServiceCall and ReadRooms method will fired equally but I am getting below result that is not correct.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void ReadRooms(int i)
{
Console.WriteLine("Reading Room::" + i);
Thread.Sleep(2000);
}
public static void CallService(int i)
{
Console.WriteLine("ServiceCall::" + i);
ReadRooms(i);
}
static void Main(string[] args)
{
Thread[] ts = new Thread[4];
for (int i = 0; i < 4; i++)
{
ts[i] = new Thread(() =>
{
int temp = i;
CallService(temp);
});
ts[i].Start();
}
for (int i = 0; i < 4; i++)
{
ts[i].Join();
}
Console.WriteLine("done");
Console.Read();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…