在socket多线程通信中,在类resourcesManager中会出现对象实例引用问题

Apr 2, 2010 at 5:54 AM

如题,在socket多线程通信中,在类resourcesManager中会出现对象实例引用问题。使用的是socket的阻塞模式。但是经过不使用extaspnet 测试,上述问题是不存在的。

测试类中的两个方法如下:

        private void ThreadFunc(object obj)
        {
            Socket currentSkt = linkSite_tb[obj] as Socket;
            while (true)
            {
                try
                {
                    int bytes;
                    byte[] packetBuff = new byte[1024];
                    bytes = currentSkt.Receive(packetBuff, packetBuff.Length, 0);
                    recvStr += Encoding.ASCII.GetString(packetBuff, 0, bytes);
                    //Alert.Show(recvStr );
                    str = Encoding.ASCII.GetString(packetBuff, 0, bytes);
                    Console.WriteLine(str);

                }
                catch (SocketException)
                {
                    Thread.CurrentThread.Abort();
                }
            }
        }

        public void StartUp()
        {
            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
            tcpl = new TcpListener(ip, port);
            tcpl.Start();
            while (true)
            {
                byte[] packetBuff = new byte[1024];
                Socket newSocket = tcpl.AcceptSocket();
                newSocket.Receive(packetBuff, packetBuff.Length, 0);
                linkSite_tb.Add(i, newSocket);
                Thread newThread = new Thread(new ParameterizedThreadStart(ThreadFunc));
                newThread.Start(i);
                i++;
            }
        }

Coordinator
Apr 2, 2010 at 11:34 AM

ResourceManager 和socket没有任何关系吧,你看ResourceManager是把自己的实例保存在当前请求的上下文中的:

        public static ResourceManager Instance
        {
            get
            {
                ResourceManager rm = HttpContext.Current.Items[ResourceManager.RESOURCE_MANAGER_CONTEXT_NAME] as ResourceManager;
                if (rm == null)
                {
                    rm = new ResourceManager();
                    HttpContext.Current.Items[ResourceManager.RESOURCE_MANAGER_CONTEXT_NAME] = rm;
                }

                return rm;
            }
        }