稳定重现bug的程序:
class Program
{
static void Main(string[] args)
{
System.Threading.Thread[] threads = new System.Threading.Thread[2];
threads[0] = new System.Threading.Thread(new ThreadStart(GetConnectionManager));
threads[1] = new System.Threading.Thread(new ThreadStart(GetConnectionManager));
threads[0].Start();
threads[1].Start();
Console.ReadKey();
}
static private void GetConnectionManager()
{
lock (typeof(Program))
{
bool hasTcpChannel = false;
foreach (var item in ChannelServices.RegisteredChannels)
{
if (item is TcpClientChannel)
{
hasTcpChannel = true;
}
}
if (!hasTcpChannel)
{
IChannel clientChannel = new TcpClientChannel();
Thread.Sleep(2000);
ChannelServices.RegisterChannel(clientChannel, false);
}
}
}
}
我们的解决方案是:
class Program
{
static void Main(string[] args)
{
System.Threading.Thread[] threads = new System.Threading.Thread[2];
threads[0] = new System.Threading.Thread(new ThreadStart(GetConnectionManager));
threads[1] = new System.Threading.Thread(new ThreadStart(GetConnectionManager));
threads[0].Start();
threads[1].Start();
Console.ReadKey();
}
static private void GetConnectionManager()
{
//加锁来保证线程安全
lock (typeof(Program))
{
bool hasTcpChannel = false;
foreach (var item in ChannelServices.RegisteredChannels)
{
if (item is TcpClientChannel)
{
hasTcpChannel = true;
}
}
if (!hasTcpChannel)
{
IChannel clientChannel = new TcpClientChannel();
Thread.Sleep(2000);
ChannelServices.RegisterChannel(clientChannel, false);
}
}
}