BUG:The channel 'tcp' is already registered.

来源:互联网 发布:linux添加路由命令 编辑:程序博客网 时间:2024/05/18 00:10

稳定重现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);                }            }         }


 

如有更好地建议,请留言!谢谢!

 

原创粉丝点击